Sql 联接表和总计
我将如何联接以下表以给出所有表的总计数Sql 联接表和总计,sql,sql-server-2014,Sql,Sql Server 2014,我将如何联接以下表以给出所有表的总计数 select (BatchIdentifier), Count(distinct BatchIdentifier) as ERTBatchCheckIdentifier from ERTBatchChecks Group By BatchIdentifier select (ERTBatchNumber), Count(distinct ERTBatchNumber) as ERTBatchNumber from ERTCl
select (BatchIdentifier),
Count(distinct BatchIdentifier) as ERTBatchCheckIdentifier
from ERTBatchChecks
Group By BatchIdentifier
select (ERTBatchNumber),
Count(distinct ERTBatchNumber) as ERTBatchNumber
from ERTClaims
Group By ERTBatchNumber
select (BatchIdentifier),
Count(distinct BatchIdentifier) as ERTBatchesIdentifier
from ERTBatches
Group By BatchIdentifier
如果只需要一个
SUM()
,则使用派生表和union all
:
SELECT Batch, SUM(Cnt) AS TotalCount
FROM (
select (BatchIdentifier) AS Batch,
Count(distinct BatchIdentifier) as Cnt
from ERTBatchChecks
Group By BatchIdentifier
union all
select (ERTBatchNumber),
Count(distinct ERTBatchNumber)
from ERTClaims
Group By ERTBatchNumber
union all
select (BatchIdentifier),
Count(distinct BatchIdentifier)
from ERTBatches
Group By BatchIdentifier
) SubCounts
GROUP BY Batch
如果需要不同“批次”的总计数,请使用union和count()
:
注意:
Union all
将保留重复项,Union
将不保留重复项。因此,对于添加计数,我们希望在两个计数相同的情况下使用Union all
。但是对于不同批次的计数,我们需要Union
,因此我们不会对同一批次进行多次计数。什么的总计数?所有记录,或组,或。。。?BatchIdentifier和ERTBatchNumber是否在表之间具有相同的值,因此分组应跨表进行?你能发布一些样本数据和预期结果吗?这些都很好,但这是我需要的。999 (3) 666(3) 123 (2). 因此,它将是所有列中每个标识符的总和,包括results@JohnMolina第一个查询应该是close,我错误地漏掉了BatchIdentifier
。为了方便起见,我将其称为Batch
。
SELECT Count(Batch) AS TotalDistinctBatches
FROM (
select distinct BatchIdentifier as Batch
from ERTBatchChecks
union
select distinct ERTBatchNumber
from ERTClaims
union
select distinct BatchIdentifier
from ERTBatches
) DistinctBatches