我正在运行查询PatientID和TXNDAte的查询,以确保他们能够每15个月完成一次任务。
ClientID TxnDate TxnCode Appt#
57 7/15/2010 V107 1
327 1/31/2011 V107 1
416 12/4/2010 V175 1
416 12/3/2011 V157 2
416 2/9/2013 V157 3
431 5/7/2011 V175 1
431 3/29/2012 V201 2
574 7/16/2011 V107 1
669 12/18/2010 V107 1
669 12/17/2011 V107 2
我使用了row_Number FUnction来获取Appt#,现在我正在寻找运行类似这样的case语句。
Case
When Appt# - 1 = 0 Then Null
When Appt# - 1 > 0 Then **DateDiff (from the present row and subtract the date from previous row)**.
这当然是我遇到问题的地方。有没有人对我如何做到这一点有任何建议?
谢谢,
答案 0 :(得分:0)
不使用LAG
或CTE
,一个简单的解决方案就是将您的桌子加入到自身......
SELECT ClientID, TxnDate, TxnCode, Appt#,
(SELECT MAX(TxnDate)
FROM data
WHERE data.ClientID = current.ClientID
AND data.TxnDate < current.TxnDate
) AS PreviousTxnDate
FROM data AS current
然后你可以将它用作生成的表来计算日期的差异......
SELECT ClientID, TxnDate, TxnCode, Appt#,
DATEDIFF(Month, PreviousTxnDate, TxnDate) AS Months
FROM (
SELECT ClientID, TxnDate, TxnCode, Appt#,
(SELECT MAX(TxnDate)
FROM data
WHERE data.ClientID = current.ClientID
AND data.TxnDate < current.TxnDate
) AS PreviousTxnDate
FROM data AS current
) dataWithPrevious
答案 1 :(得分:0)
你的输出是什么样的?
你可以做这样的事情,
Declare @t table (ClientID int, TxnDate date,TxnCode varchar(10), Appt# int)
insert into @t values(57,'7/15/2010','V107',1),(327,'1/31/2011','V107',1),
(416,'12/4/2010','V175',1),
(416,'12/3/2011','V157',2),
(416,'2/9/2013','V157',3),
(431,'5/7/2011','V175',1),
(431,'3/29/2012','V201',2),
(574,'7/16/2011','V107',1),
(669,'12/18/2010','V107',1),
(669,'12/17/2011','V107',2)
select *,0 Nocloumn from @t where clientid not in (select clientid from @t where Appt# >1)
union all
select a.*, Case
When a.Appt# - 1 = 0 Then Null
When a.Appt# - b.Appt# =1 Then DateDiff (day,b.TxnDate,a.TxnDate) end Nocloumn
from @t a
inner join @t b on a.ClientID=b.ClientID and a.Appt#>b.Appt#
where a.Appt# - b.Appt#=1