1

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

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

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

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

4

4 回答 4

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
于 2013-07-01T18:57:16.880 回答
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
于 2013-07-01T19:46:31.857 回答
0

也许你需要联合事物......

select * from (
SELECT 'revenue' tbl, count(*), constituentid id FROM REVENUE
union
SELECT 'constituent', count(*), id  FROM CONSTITUENT
)
where id = ?
于 2013-07-01T18:56:43.043 回答
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

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

于 2013-07-01T19:05:09.833 回答