在单个查询中收集多个表的计数

时间:2013-07-01 18:52:38

标签: sql sql-server

我需要从多个表(通过ID列相关)收集计数,所有这些都在一个查询中,我可以参数化以便在其他地方的某些动态SQL中使用。这就是我到目前为止所做的:

SELECT  revenue.count(*),
        constituent.count(*) 
FROM REVENUE
INNER JOIN CONSTITUENT 
    ON REVENUE.CONSTITUENTID = CONSTITUENT.ID

这不起作用,因为它不知道如何处理计数,但我不确定使用正确的语法。

为了澄清一点,我不希望每个ID有一条记录,而是每个表的总计数,我只需将它们合并为一个脚本。

4 个答案:

答案 0 :(得分:2)

这样可行:

select MAX(case when SourceTable = 'Revenue' then total else 0 end) as RevenueCount,
       MAX(case when SourceTable = 'Constituent' then total else 0 end) as ConstituentCount
from (
    select count(*) as total, 'Revenue' as SourceTable
    FROM revenue
    union
    select count(*), 'Constituent'
    from Constituent
) x

答案 1 :(得分:0)

也许你需要结合......

select * from (
SELECT 'revenue' tbl, count(*), constituentid id FROM REVENUE
union
SELECT 'constituent', count(*), id  FROM CONSTITUENT
)
where id = ?

答案 2 :(得分:0)

您想要每个ID一条记录吗?

SELECT coalesce(c.id, r.ConstituentID) "ID", COUNT(r.ConstituentID) "Revenue", COUNT(c.ID) "Constituent"
FROM Revenue r
FULL JOIN constituent c on c.id = r.ConstituentId
GROUP BY coalesce(c.id, r.ConstituentID)

或者您想要给定ID的计数吗?

SELECT c.ID "ID", COUNT(r.ConstituentID) "Revenue", COUNT(c.ID) "Constituent"
FROM Revenue r
INNER JOIN constituent c on c.id = r.ConstituentId
WHERE c.ID = @ID
GROUP BY c.id

或者你想要两个表中的总计数?

SELECT 'Revenue' "Table", COUNT(*) "Rows" FROM Revenue
UNION
SELECT 'Constituents', COUNT(*) FROM Constituents

请注意,在最后,表格相关的事实是无关紧要的。

答案 3 :(得分:0)

你说你想用动态sql做这件事。这是你在找什么?

DECLARE @sql nvarchar(4000)

SELECT @sql = COALESCE(@sql + N' UNION ALL '+CHAR(13),'') + N'SELECT '''+QUOTENAME(table_name)+''',COUNT(*) FROM '+QUOTENAME(table_name)
FROM (VALUES('t1'),('t2'),('t3')) table_list(table_name)

PRINT @sql