2017-05-12 107 views
0

我將如何加入以下表格以給出所有表格的總計數。加入表格和總計

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

總計什麼?所有記錄,組或...? BatchIdentifier和ERTBatchNumber在表中有相同的值,所以分組應該跨表?你能發佈一些樣本數據和預期結果嗎? –

回答

0

如果你只是想一個SUM()然後使用派生表和union all:如果你想在不同的「批次」,然後使用工會和COUNT()的總數

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 

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,所以我們不會多次計算同一批次。

+0

這些都很棒,但這是我需要的。 999(3)666(3)123(2)。因此,這將是所有列中每個標識符的總和,包括結果中的標識符。 –

+0

@JohnMolina第一個查詢應該是關閉的,我錯誤地忽略了「BatchIdentifier」。我稱之爲「Batch」是爲了方便。 –