这是我的数据库结构。 表名LOPList:
a busy cat http://i65.tinypic.com/2ebtyr9.png
我有这个SQL:
select LOPID, EmpId,
max(case when LOPStatus = 'Y' then TimeUpdated end) as time_start,
max(case when LOPStatus = 'N' then TimeUpdated end) as time_end
from MultipleLOPStatus
where JobID = 83
group by LOPID
结果是
LOPID | EmpId | time_start | time_end
33 | 28 | 2016-03-27T09:33:05-03:00 | 2016-03-27T11:49:17-03:00`
我希望结果如下:
LOPID | EmpId | time_start | time_end
33 | 28 | 2016-03-27T09:23:17-03:00 | 2016-03-27T09:31:59-03:00
33 | 28 | 2016-03-27T09:32:30-03:00 | 2016-03-27T11:49:17-03:00
33 | 30 | 2016-03-27T09:33:05-03:00 | 2016-03-27T11:48:53-03:00 `
我们如何实现这一目标?
答案 0 :(得分:3)
如果我理解正确,你只想获得每个相应time_start的time_end。在这种情况下,您不需要使用条件聚合,您可以使用相关查询来实现此目的:
SELECT s.LOPID, s.EmpId,s.timeUpdated as time_start,
(SELECT MIN(timeUpdated) FROM MultipleLOPStatus t
WHERE s.LOPID = t.LOPID and t.empid = s.empid and t.LOPStatus = 'N'
AND t.timeUpdated > s.TimeUpdated) as time_end
from MultipleLOPStatus s
where s.JobID = 83
AND s.LOPStatus = 'Y'