-5

我想编写一个查询来计算基于月份的总生日蛾。这是样本数据。两个人的生日是 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
.....
4

3 回答 3

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

于 2012-04-11T18:07:59.967 回答
1

在 MySQL 中,你会这样做:

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

但是,为了获得“缺失日期”,您必须生成数据,因为01/1980据我所知,它不在任何表格中。检查这个答案,看看如何。

于 2012-04-11T18:05:30.227 回答
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
于 2012-04-11T17:56:30.927 回答