需要统计同一模式的多个表

时间:2017-11-07 15:11:49

标签: sql-server

我需要一次性查看以下四个查询的总数。

SELECT count(companyid) FROM [CoreReferenceStaging].[dbo].[FinData2000_1]
SELECT count(companyid) FROM [CoreReferenceStaging].[dbo].[FinData2000_2]
SELECT count(companyid) FROM [CoreReferenceStaging].[dbo].[FinData2000_3]
SELECT count(companyid) FROM [CoreReferenceStaging].[dbo].[FinData2000_4]

我尝试了以下操作,但是我收到了错误#39;)'。

附近的语法不正确
SELECT count(companyid) FROM 
(
SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_1]
union all
SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_2]
union all
SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_3]
union all 
SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_4]
)

1 个答案:

答案 0 :(得分:4)

你快到了

SELECT sum(c) FROM 
(
 SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_1]
 union all
 SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_2]
 union all
 SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_3]
 union all 
 SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_4]
) a

ps,有很多方法可以为这只猫提供皮肤:

SELECT
  (SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_1]) +
  (SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_2]) +
  (SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_3]) +
  (SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_4])



SELECT a+b+c+d FROM 
 (SELECT count(companyid) a FROM [CoreReferenceStaging].[dbo].[FinData2000_1]) aa
 CROSS JOIN
 (SELECT count(companyid) b FROM [CoreReferenceStaging].[dbo].[FinData2000_2]) bb
 CROSS JOIN
 (SELECT count(companyid) c FROM [CoreReferenceStaging].[dbo].[FinData2000_3]) cc
 CROSS JOIN 
 (SELECT count(companyid) d FROM [CoreReferenceStaging].[dbo].[FinData2000_4]) dd

SELECT count(companyid) FROM 
(
 SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_1]
 union all
 SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_2]
 union all
 SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_3]
 union all 
 SELECT companyid FROM [CoreReferenceStaging].[dbo].[FinData2000_4]
) a

要记住的关键事项:

  • 子查询总是需要SQLServer中的别名(除非它们在选择列表中,如示例2所示)
  • 如果公司ID为空,则不会计入
  • 尝试计算已建立索引的列,因为它应该更快
  • 我通常更喜欢保持子查询输出的数据集尽可能小,因为如果所有外部查询都要计算它们,或者以某种方式对它们进行分组,则子查询中没有任何内容向外部查询提供十亿行 - 在子查询中进行分组。这通常使SQL更易于阅读/理解,并且可以防止服务器端上的过多资源消耗,特别是如果涉及到其他大型数据集的连接,然后是计数/分组。构建到RDBMS中的查询分析器不能总是重写分组嵌套查询,因此它们更有效率
  • 此答案中没有列表详尽无遗:)