从2列开始接下来的7天生日

时间:2012-08-15 20:11:41

标签: mysql sql

我需要在接下来的7天内查询我的数据库中的生日 - 生日日期分为两列

  Name  Day   Month   
  Peter 15    8       
  Susi  20    8      
  Thor  14    9

查询=未来7天有生日的人 返回

Peter 15 - 8   
Susi  20 - 8

欢迎任何帮助 - 问候 的Thorsten

2 个答案:

答案 0 :(得分:4)

您没有指定RDBMS,但这应该在 SQL Server 中返回您想要的结果。这些将检查表中的月份是否小于当月,如果是,那么它将使用下一年:

select *
from 
(
    select name,
        cast(case 
                when datepart(month, getdate()) > [month] 
                 and datepart(day, getdate()) > [day]
                then cast(datepart(year, dateadd(year, 1, getdate())) as varchar(4))
                else cast(datepart(year, getdate()) as varchar(4)) end + '-'
            + cast([month] as varchar(2)) + '-'
            + cast([day] as varchar(2)) as datetime) bd
    from t1
) x
where datediff(day, getdate(), bd) >= 0 
  and datediff(day, getdate(), bd) < 7

请参阅SQL Fiddle with Demo

或者:

select *
from 
(
    select name,
        cast(case 
        when datepart(month, getdate()) > [month] 
            and datepart(day, getdate()) > [day]
        then cast(datepart(year, dateadd(year, 1, getdate())) as varchar(4))
        else cast(datepart(year, getdate()) as varchar(4)) end + '-'
    + cast([month] as varchar(2)) + '-'
    + cast([day] as varchar(2)) as datetime) bd
    from t1
) x
where bd >= DateAdd(day, DateDiff(day, 0, getdate()), 0)
    and bd < DateAdd(day, DateDiff(day, 0, getdate()), 7)

MySQL版本:

SELECT *
FROM
(
  select name,
    str_to_date(concat(case 
      when month(current_date()) > month
           and day(current_date()) > day
      then year(date_add(current_date, interval 1 year))
      else year(current_date()) 
    end, '-', month, '-', day), '%Y-%m-%d') birthdate
  from t1
) x
where birthdate >= Date(current_date())
  and birthdate < Date(Date_Add(current_date(), interval 7 day))

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

从@bluefeet回答第二个选择语句,您可以执行以下操作:

select * 
from  
( 
    select name,
        case when(
         cast(cast(datepart(year, getdate()) as varchar(4)) + '-' 
        + cast([bmonth] as varchar(2)) + '-' 
        + cast([bday] as varchar(2)) as datetime) > getdate())
        THEN
            cast(cast(datepart(year, getdate()) as varchar(4)) + '-' 
            + cast([bmonth] as varchar(2)) + '-' 
            + cast([bday] as varchar(2)) as datetime)

        ELSE

            cast(cast(datepart(year, getdate())+1 as varchar(4)) + '-' 
            + cast([bmonth] as varchar(2)) + '-' 
            + cast([bday] as varchar(2)) as datetime)
        END
        as bd 
    from @Names 
) x 
where bd >= DateAdd(day, DateDiff(day, 0, GETDATE()), 0) 
    and bd < DateAdd(day, DateDiff(day, 0, GETDATE()), 7)