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\"
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()
.