注册 登录
编程论坛 SQL Server论坛

sql多种情况返回一个值问题

dephy 发布于 2009-10-15 09:03, 686 次点击
表 字段  ID date1 date2 date3 day

如果date3为空,date2不为空, day= ((Now-date2)+(date2-date1))/365;
如果date3不为空,date2为空, day= (date3-date1)/365;
sql怎么写
2 回复
#2
Vitamin19992009-10-15 10:27
日期是不能直接相加减的,你必须指定是什么相加减,是日期,月份还是年份之类的,看你的题意,应该是日期之间的换算吧,以下是SQL

select case
        when date3 is null and date2 is not null then (datediff(dd,date2,getDate()))+(datediff(dd,date1,date2))/365
        when date3 is not null and date2 is null then (datediff(dd,date1,date3))/365
        end as day
from 表
#3
我是傻逼2009-10-16 20:47
select case when date3 is null then (case when date2 is not null then ((Now-date2)+(date2-date1))/365)
           else (case when data2 is not null then (date3-date1)/365) end as day from table where.....
1