0

I have a dataset and I need to calculate date difference. I need a generic query as dataset will be different every day.

Here is my Dataset

**Client Number    :  Status  :    StatusDate**
   123456           Admit       2012-01-18
   123456           Accepted    2012-01-15
   123456           Offered     2012-01-10

   567899           Admit       2012-01-11
   567899           Accepted    2012-01-07
   567899           Offered     2012-01-05

   987342           Admit       2012-01-24
   987342           Accepted    2012-01-24
   987342           Offered     2012-01-21

Above is the sample data and as I said data will change on daily bases. There will always be three entered for specific Client number as you can see above with always three status in the above following order.

What I need is to calculate the days different between Offered to Accepted and Accepted to Admit. The above result set should look like this. Three Columns

**ClientNumber : Date Diff Betw Offeres & Accepted : Date Diff Betw Accepted & Admited** 
   123456                     5 Days                           3 Days
   567899                     2 Days                           4 Days
   987342                     3 Days                           0 Days

I need generic query and as I said the each client number will have three status.

Thanks in advance.

2 Answers 2

1

You'll have to do a self join. Here is a generic example.

select t1.clientnumber, datediff(day, t1.statusdate, t2.statusdate) OfferToAccept
from yourtable t1 join yourtable t2 on t1.clientnumber = t2clientnumber
and t1.status = 'Offered' and t2.status = 'Accepted'

where whatever

It's a similar thing for the other interval which is probably mistyped in your question. It says "Date Diff Betw Accepted & Accepted"

1
  • yes but i need one query ... i fixed the third column it should be accepted & admitted.
    – Ally
    Feb 8, 2013 at 2:26
0

Query:

SQLFIDDLEExample

SELECT t1.[Client Number],
       MAX(datediff(DAY, t1.statusdate, t2.statusdate)) [Offeres & Accepted],
       MAX(datediff(DAY, t3.statusdate, t1.statusdate)) [Accepted & Admited]
FROM Table1 t1
LEFT JOIN Table1 t2 ON t1.[Client Number] = t2.[Client Number]
AND t1.status = 'Offered'
AND t2.status = 'Accepted'
LEFT JOIN Table1 t3 ON t1.[Client Number] = t3.[Client Number]
AND t1.status = 'Admit'
AND t3.status = 'Accepted'
GROUP BY t1.[Client Number] 

Result:

| CLIENT NUMBER | OFFERES & ACCEPTED | ACCEPTED & ADMITED |
-----------------------------------------------------------
|        123456 |                  5 |                  3 |
|        567899 |                  2 |                  4 |
|        987342 |                  3 |                  0 |
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.