sql:根据月份计算总生日蛾

时间:2012-04-11 17:50:10

标签: sql

我想编码一个查询来计算基于月份的总生日蛾。这是样本数据。两个人的生日是1980年4月。

如何撰写此查询?

John    02/21/1980
Peter   02/22/1980
Lucy    04/21/1980

------ result -----
01/1980     0
02/1980     2
03/1980     0
04/1980     1
05/1980     0
.....

3 个答案:

答案 0 :(得分:3)

你可以像这样循环每个月:

DECLARE @month INT 
DECLARE @year INT
DECLARE @result TABLE (MonthYear varchar(7),BirthdaysCount INT)
SET @month = 1
SET @year = 1980

WHILE(@month < 13)
  BEGIN
    INSERT INTO @result
    SELECT (CAST(@month as VARCHAR) + '/' + CAST(@year as VARCHAR)),
            COUNT(*)
    FROM test
    WHERE MONTH(birth) = @month AND YEAR(birth) = @year
    SET @month = @month + 1
  END

select * from @result

请参阅小提琴:http://sqlfiddle.com/#!3/20692/2

答案 1 :(得分:1)

在MySQL中你会这样做:

select concat(month(dob), '/', year(dob)) monthYear, count(*) cnt from t
group by monthYear
order by year(dob), month(dob)

但是,为了获得“缺少日期”,您必须生成数据,因为01/1980不在任何表格中,据我所见。请查看此answer以了解具体方法。

答案 2 :(得分:0)

sql-server

的情况如何?
create table #temp
(
    name varchar(50),
    DOB datetime
)

insert into #temp values ('john', '2/21/1980')
insert into #temp values ('peter', '2/22/1980')
insert into #temp values ('lucy', '4/21/1980')

select convert(varchar(2), MONTH(DOB)) + '/' + Convert(varchar(4), YEAR(DOB)) as [MM/YYYY]
    , count(*) as TotalCount
from #temp
group by convert(varchar(2), MONTH(DOB)) + '/' + Convert(varchar(4), YEAR(DOB))

drop table #temp

编辑 - 这将为您提供表格中日期中包含的日期的所有记录。它将使用表格中的最小/最大日期来获取日期范围,然后使用此范围获取每个月的生日计数:

create table #temp
(
    name varchar(50),
    DOB datetime
)

insert into #temp values ('john', '2/21/1980')
insert into #temp values ('peter', '2/22/1980')
insert into #temp values ('lucy', '4/21/1980')

;with cte as
(
    select min(DOB) as MinDate, max(DOB) as MaxDate
    from #temp
    union all
    SELECT dateadd(mm, 1, t.MinDate), t.MaxDate
    from cte t
    where dateadd(mm, 1, t.MinDate) <= t.MaxDate
)
select convert(varchar(2), MONTH(c.MinDate)) + '/' + Convert(varchar(4), YEAR(c.MinDate))
    , IsNull(t.TotalCount, 0) as TotalCount
from cte c
LEFT JOIN 
(
    SELECT convert(varchar(2), MONTH(DOB)) + '/' + Convert(varchar(4), YEAR(DOB)) as [MM/YYYY]
        , count(*) as TotalCount
    FROM #temp 
    group by convert(varchar(2), MONTH(DOB)) + '/' + Convert(varchar(4), YEAR(DOB))
) t
    on convert(varchar(2), MONTH(C.MinDate)) + '/' + Convert(varchar(4), YEAR(C.MinDate))
        = t.[MM/YYYY]

drop table #temp