在其他groupby组中添加count = 0的新行

时间:2015-07-15 02:37:01

标签: mysql sql sql-server

我有这个表:

||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

的行

1 个答案:

答案 0 :(得分:1)

首先,您要生成statusgroup的所有组合。您可以使用CROSS JOIN执行此操作。然后,在您的桌面上执行LEFT JOIN以获取COUNT

SQL Fiddle

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]

使用子查询:

SQL Fiddle

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]