使用SQL查找日期和月份的所有组合

时间:2018-10-27 17:44:21

标签: sql sql-server group-by

我想找出一年中每天的员工生日总数。

我使用以下查询获取结果:

Select S.birthday_month,S.birthday_day,COUNT(id) AS 'No of Birthdays'
            FROM Students S
            GROUP BY S.birthday_month,S.birthday_day
            ORDER BY S.birthday_month,S.birthday_day

结果

 birthday_month    birthday_day      No of Birthdays
    April            16                 2
    May               1                  1
    June              5                  1
    September         22                 1

我真正想要的是月份和日期的所有可能组合,如果不存在,则将生日数中的值设为0。

这是我想要的输出

   birthday_month    birthday_day      No of Birthdays
    Jan                  1                0
    Jan                  2                0
    Jan                  3                0
                  etc
                  etc
    April              16                 2
    May                1                  1
    June               5                  1
    September          22                 1
                  etc
                  etc
    Dec                30                 0
    Dec                31                 0

1 个答案:

答案 0 :(得分:2)

解决方案是left join。 。 。但您需要列出日期。一种方法是生成日期并去除年份:

with dates as (
      select cast('2000-01-01' as date) as dte, datename(month, '2000-01-01') as mon, 1 as day, 1 as lev
      union all
      select dateadd(day, 1, dte), datename(month, dateadd(day, 1, dte)), day(dateadd(day, 1, dte)) lev + 1
      from dates
      where dte < '2000-12-31'
     )
select d.mon, d.day, count(s.birthday_month)
from dates d left join
     students s
     on s.birthday_month = d.mon and s.birthday_day = d.day
group by d.mon, d.day
order by d.lev
option (maxrecursion 0);