SQL查询在ID上组合行

时间:2014-05-14 17:23:12

标签: sql database

我正在尝试在报价历史记录表上运行查询,并尝试了解我们的响应时间。

我有一个名为status_history的表,我希望为同一个引号返回两行之间的日期差异。

我有以下查询:

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')

我正在尝试将最终查询输出为:

quote_number| hour_difference

我很难按照我想要的方式输出它,因为每个quoteid可以有多行,因为它可以多次更改状态。就像在这里看到的那样:

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

最后,我想检查一下所有状态变化之间的时间,但现在这样才能让我继续。

再次感谢!

1 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

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;