Question

I am running a Query that is looking at the PatientID, and TXNDAte to ensure that they are in compliance of getting things done every 15 months.

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

I have used a row_Number FUnction to get the Appt# and am now looking to run a case statement that does something like this.

Case
   When Appt# - 1 = 0 Then Null
   When Appt# - 1 > 0 Then **DateDiff (from the present row and subtract the date from previous row)**.

This is of course where I am having issues. Does anyone have any suggestions on how I might do this?

Thanks,

Was it helpful?

Solution

Without using LAG or CTE's, a simple solution is to join your table to itself...

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

Then you could use this as a generated table to compute the difference in dates...

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

OTHER TIPS

what is your output looklike ?

you can do something like this,

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top