日期:2014-05-18  浏览次数:20446 次

sqlserver 中求一简单sql 与日期有关
sqlserver 资料库

有这样一个表 test
有栏位 其中date1 与 date2 为日期型

id date1 date2  
1 2011-11-08 NULL
2 NULL 2011-10-03
3 NULL NULL
4 2011-10-09 2011-11-08
5 2012-01-09 2017-11-07
现在要求得到数据

id date1 date2 a1 b1
1 2012-11-08 NULL N N
2 NULL 2011-10-03 N Y
3 NULL NULL N N
4 2011-10-09 2011-11-08 Y Y
5 2012-01-09 2017-11-07 Y N
其中 当 date1 中的日期 小于当前日期+180 天时,a1中显示 Y 否则显示N
其中 当 date2 中的日期 小于当前日期+30 天时,a2中显示 Y 否则显示N



------解决方案--------------------
SQL code
select *,
       a1=case when date1<dateadd(day,180,getdate()) then 'Y' else 'N' end,
       a2=case when date2<dateadd(day,180,getdate()) then 'Y' else 'N' end
from tb

------解决方案--------------------
SQL code
create table tb(id int,date1 datetime,date2 datetime)
insert into tb
 select 1,'2011-11-08',null union
 select 2,null,'2011-10-03' 
 
select *,
       a1=case when date1<dateadd(day,180,getdate()) then 'Y' else 'N' end,
       a2=case when date2<dateadd(day,30,getdate()) then 'Y' else 'N' end
from tb

/*
id          date1                   date2                   a1   a2
----------- ----------------------- ----------------------- ---- ----
1           2011-11-08 00:00:00.000 NULL                    Y    N
2           NULL                    2011-10-03 00:00:00.000 N    Y

(2 行受影响)

------解决方案--------------------
SQL code
select *,
       a1=case when datediff(day,date1,getdate())>180 then 'Y' else 'N' end,
       a2=case when datediff(day,date1,getdate())>180 then 'Y' else 'N' end
from tb

------解决方案--------------------
楼主的结果不对吧
SQL code

if object_id('test') is not null
   drop table test
go
create table test
(
 id int identity(1,1),
 date1 datetime,
 date2 datetime
)
go
insert into test(date1,date2)
select '2011-11-08',null union all
select null,'2011-10-03' union all
select null,null union all
select '2011-10-09','2011-11-08' union all
select '2012-01-09','2017-11-07'
go
select * ,
       a1=case when date1<dateadd(dd,180,getdate()) then 'Y' else 'N' end,
       a2=case when date2<dateadd(dd,30,getdate()) then 'Y' else 'N' end
from test
go
/*
id          date1                   date2                   a1   a2
----------- ----------------------- ----------------------- ---- ----
1           2011-11-08 00:00:00.000 NULL                    Y    N
2           NULL                    2011-10-03 00:00:00.000 N    Y
3           NULL                    NULL                    N    N
4           2011-10-09 00:00:00.000 2011-11-08 00:00:00.000 Y    Y
5           2012-01-09 00:00:00.000 2017-11-07 00:00:00.000 Y    N

(5 行受影响)
*/