我如何加入以下表格以提供所有表格的总计数。
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
答案 0 :(得分:0)
如果您只想要一个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()
:
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
注意:Union all
会保留重复项,Union
则不会。因此,为了添加计数,我们希望在两个计数相同的情况下使用Union all
。但是,为了计算不同的批次,我们需要Union
,因此我们不会多次计算同一批次。