我试图获得具有DateOrderID的日期之间的月数,以便将它们放入订单中(最早的日期是1,第二个是2等)。我的问题是,因为手动输入DateOrder ID我有一些记录,其中缺少DateOrderID,所以我的查询返回该字段的NULL。我的(虚拟)代码是:
Select a.PersonID
,a.Date
,a.DateOrderID
,case when a.DateOrderID = 1 then 'First Date'
else convert(varchar(5),datediff(month, b.Date, a.Date)) end as Months_Between
from OrderTable a
left join
OrderTable b
on a.PersonID = b.PersonID and a.DateOrderID = b.DateOrderID +1
目前返回
PersonID Date DateOrder Months_Between
101 20150401 1 First Date
101 20160621 2 14
101 20170301 3 9
102 20110506 1 First Date
102 20140817 3 NULL
102 20160906 4 25
我想要的结果会将PersonID 102的NULL替换为' Missing ID'。我在案例陈述中尝试过一些事情,但没有成功,有什么想法吗?
答案 0 :(得分:0)
SELECT a.PersonID ,
a.Date ,
a.DateOrderID ,
CASE
WHEN a.DateOrderID = 1
THEN 'First Date'
ELSE ISNULL(CONVERT(VARCHAR(5),DATEDIFF(MONTH, b.Date, a.Date)),'Missing Date')
END AS Months_Between
FROM OrderTable a
LEFT JOIN OrderTable b
ON a.PersonID = b.PersonID
AND a.DateOrderID = b.DateOrderID +1