协调SQL Server中不同表的计数

时间:2018-05-21 18:59:47

标签: sql-server stored-procedures

我正在尝试协调SQL Server中不同表的计数。我的表结构类似于:

ID (Auto identity) DivID TableName StagingCount DWCount DateCounted

我可以通过使用类似

的方式获得计数
select DivID, 'TableName', Count(*) from StagingTable Group BY DivID

UNION

SELECT DivID, 'TableName', Count(*) from DWTable Group By DivID

但问题是我得到了多行的计数。

DivID     TableName       Cnt    

1         Customer       2833    
1         CustomerDW     2833

我最想得到的是:

DivID     TableName        StagingCount     DWCount
  1       Customer           2833            2833
  1       Product            1234            5678
  1       Address            8765            4321

如何在SQL Server中实现此目的?

1 个答案:

答案 0 :(得分:2)

您可以合并union通过subquery进行条件汇总

select DivID, 
       max(case when TableName = 'Customer' then cnt end) StagingCount,
       max(case when TableName = 'CustomerDW' then cnt end) DWCount,
       max(case when TableName = 'table3' then cnt end) table3count,
       . . .
from ((select DivID, TableName, Count(*) cnt 
       from StagingTable 
       Group BY DivID
       ) union 
       (select DivID, TableName, Count(*) 
        from DWTable 
        Group By DivID
       )
      )t
group DivID;