如何在sql中正确使用group by子句

时间:2016-02-12 03:16:24

标签: sql

我使用以下查询来获得预期的输出,但无法正常工作。

with f1 as 
(
    select 
        case when f.eventid = 5 then f.timestamps end as starttime,
        case when f.eventid = 6 then f.timestamps end as endtime,
        f.instanceidentifier as identifier
    from 
        frarecord f 
)
select 
    starttime, endtime, identifier 
from f1

我得到了以下输出:

enter image description here

但是输出应该按标识符分组。

我还尝试使用group by子句作为标识符。例外情况说我也要按开始时间和结束时间进行分组。

有没有解决方案?

注意:此问题与How can I calculate average with condition in sql密切相关:)

1 个答案:

答案 0 :(得分:2)

尝试使用聚合:

with f1 as (
      select (case when f.eventid=5 then f.timestamps end) as starttime,
             (case when f.eventid=6 then f.timestamps end) as endtime,
            f.instanceidentifier as identifier
      from frarecord f
     )
select min(starttime) as starttime, max(endtime) as enddtime, identifier
from f1
group by identifier;