0

我需要查询我的数据库关于未来 7 天的生日 - 生日日期分为两列

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

查询 = 下一个 7 天谁过生日 返回

Peter 15 - 8   
Susi  20 - 8

欢迎任何帮助 - 问候托尔斯滕

4

2 回答 2

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

或者:

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

于 2012-08-15T20:27:57.520 回答
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) 
于 2012-08-15T20:52:44.293 回答