سؤال

I am trying to run a query on my quote history table and trying to get an understanding of our response time.

I have a table named status_history and I wish to return the date difference between two rows for the same quote.

I have the following query:

SELECT
    quote_number,
    status,
    date,
    DATEDIFF
    (hh,
    (SELECT dateEntered 
            FROM status_history 
            WHERE status = 'Submitted'),
    (SELECT dateEntered 
            FROM status_history 
            WHERE status = 'Accepted')) as hour_difference

FROM 
    status_history

WHERE 
    status in ('Submitted','Accepted')

I am trying to get the final query to output like this:

quote_number| hour_difference

I am having a hard time getting this to output the way I want, because each quoteid can have multiple rows, because it can have a status change multiple times. Like seen here:

quote_number |  status     |  date
---------------------------------------------------
1234         | Submitted   |  2014-05-12 00:00:00.000
1234         | Accepted    |  2014-05-13 00:00:00.000
1234         | Complete    |  2014-05-14 00:00:00.000
1234         | Incomplete  |  2014-05-15 00:00:00.000

Eventually, I would like to check for the time between all status changes, but just this for now should get me going.

Thanks again!

هل كانت مفيدة؟

المحلول

Does this do what you want?

SELECT quote_number, 
       DATEDIFF(hh,
                max(case when status = 'Submitted' then dateEntered end),
                max(case when status = 'Accepted' then dateEntered end)
               ) as hour_difference
FROM status_history
WHERE status in ('Submitted','Accepted')
GROUP BY quote_number;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top