Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 协调SQL Server中不同表的计数_Sql Server_Stored Procedures - Fatal编程技术网

Sql server 协调SQL Server中不同表的计数

Sql server 协调SQL Server中不同表的计数,sql-server,stored-procedures,Sql Server,Stored Procedures,我正在尝试协调SQL Server中不同表的计数。我的表格结构类似于: ID(自动标识)DivID TableName StagingCount DWCount DateCounted 我可以用下面的方法得到计数 select DivID, 'TableName', Count(*) from StagingTable Group BY DivID UNION SELECT DivID, 'TableName', Count(*) from DWTable Group By DivID 但

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

ID(自动标识)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中实现这一点?

您可以通过
子查询组合您的
联合
,以执行条件聚合

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;

数据仓库中的所有表格都附加了
DW
?您确定此查询正在运行吗?我很确定SQL Server应该对缺少的group by犹豫不决。暂存表和DW表之间的区别在于,暂存表都附加了“暂存”一词。例如,DW上的Products表在database.Correct中会有相应的ProductsStaging表。那边的人不见了。我将编辑帖子。对于所有的DivID,DWCount列返回Nulls@rvphx. . . 导致无效
表名的原因
!!在
max中提供有效的表名(当TableName='Customer'然后是cnt end时为这种情况)
得到了。我修好了,效果很好。因此,如果我需要向列表中添加更多的表,这将如何改变?这将增加输出列的数量。当tablename出现时,我们不能做一些类似case的事情吗?@rvphx。我实际上混淆了表结构和联合查询。我没有发现他们之间有任何联系。所以,我的评论可能会放错地方。