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

前端 未结 4 1290
北海茫月
北海茫月 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:59

    Assuming that all the years and age groups are in the table (some row for the table), then you can do this just with this table. The idea is to generate all the rows using a cross join and then use a left join to bring in the values you want:

    select y.year, ag.age_group, count(u.year) as usercount
    from (select 2013 as year) y cross join
         (select distinct age_group from users) ag left join
         users u
         on u.year = y.year and u.age_group = ag.age_group and
            u.primary_group = 'NT'
    group by y.year, ag.age_group;
    

    I don't know what sum(users) is supposed to be. If you do indeed have a column users.users, then use it with sum(). It looks like you really want count().

提交回复
热议问题