How can I create a row for values that don't exist and fill the count with 0 values?

前端 未结 4 1303
北海茫月
北海茫月 2021-01-26 10:23

In SQL Server, I\'m running a query on users age groups on data where, for some years, there are zero users per age group. For example there were users in 2013 in the \"18-21\"

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-26 10:37

    I assume you have another table that contain all rows Age Group.

    TABLE NAME: AGEGROUPS

    AGE_GROUP
    18-21
    22-25
    25-28
    

    Try this:

    SELECT '2014' AS YEAR, AG.AGE_GROUP, COALESCE(TB.usercount, 0) AS usercount
    FROM (
        SELECT YEAR, AGE_GROUP, SUM(USERS) as usercount,
        FROM USERS
        WHERE YEAR = '2014'
        AND PRIMARY_GROUP = 'NT'
        GROUP BY YEAR, AGE_GROUP
    ) AS TB
    RIGHT JOIN AGEGROUPS AG ON TB.AGE_GROUP=AG.AGE_GROUP
    

提交回复
热议问题