我有这个表:
||ID || Group || Status
|| 1 || AAAA || aaaaa
|| 2 || AAAA || bbbbb
|| 3 || BBBB || aaaaa
|| 4 || BBBB || bbbbb
|| 5 || BBBB || aaaaa
|| 6 || BBBB || ccccc
|| 7 || BBBB || ddddd
我想要查询结果:
|| Status || Group || Count(Status)
|| aaaaa || AAAA || 1
|| bbbbb || AAAA || 1
|| ccccc || AAAA || 0
|| ddddd || AAAA || 0
|| aaaaa || BBBB || 2
|| bbbbb || BBBB || 1
|| ccccc || BBBB || 1
|| ddddd || BBBB || 1
我试过了:
select status, count(status), group
from TABLE
group by status, group
但是这段代码不能添加count = 0
的行答案 0 :(得分:1)
首先,您要生成status
和group
的所有组合。您可以使用CROSS JOIN
执行此操作。然后,在您的桌面上执行LEFT JOIN
以获取COUNT
WITH Cte AS(
SELECT
a.[group], b.[status]
FROM (
SELECT DISTINCT [group] FROM YourTable
)a
CROSS JOIN (
SELECT DISTINCT [status] FROM YourTable
)b
)
SELECT
c.[status],
c.[group],
ISNULL(COUNT(t.Id), 0) AS StatusCount
FROM Cte c
LEFT JOIN YourTable t
ON t.[status] = c.status
AND t.[group] = c.[group]
GROUP BY c.[status], c.[group]
使用子查询:
SELECT
c.[status],
c.[group],
ISNULL(COUNT(t.Id), 0) AS StatusCount
FROM (
SELECT * FROM(
SELECT
a.[group], b.[status]
FROM (
SELECT DISTINCT [group] FROM YourTable
)a
CROSS JOIN (
SELECT DISTINCT [status] FROM YourTable
)b
)t
) c
LEFT JOIN YourTable t
ON t.[status] = c.status
AND t.[group] = c.[group]
GROUP BY c.[status], c.[group]