我有以下查询数据的要求:
如果一个组中存在完全事件,我希望找到组中最后一个事件和第一个事件之间的时间差。
ID Time Events
---------------------------------------
1 11/08/2013 00:06:51 cancel
1 11/08/2013 00:06:51 ans
1 11/08/2013 00:06:38 notification
1 11/08/2013 00:06:38 call
1 11/08/2013 00:06:38 notification
1 11/08/2013 00:06:38 active
2 11/08/2013 00:06:30 free
2 11/08/2013 00:06:30 **complete**
2 11/08/2013 00:06:13 call
2 11/08/2013 00:06:13 notification
2 11/08/2013 00:06:13 notification
2 11/08/2013 00:06:13 active请帮助我进行SQL查询。
发布于 2018-07-02 15:36:55
你可以这样做:
SELECT id, datediff(minute, min(time), max(time)) as timediff
FROM eventtable
WHERE id in (SELECT id FROM eventtable WHERE Events = 'complete')
GROUP BY id发布于 2018-07-02 16:07:08
根据我对您的问题的理解(根据您的澄清进行修改),得到您想要的内容是非常简单的:首先,您想要Events字段包含“完整”的任何项。这个字段似乎是文本,因此您可能需要使用LIKE操作符来获取所需的记录:
select *
from Items
where upper(Events) like '%COMPLETE%'但是,您似乎需要组中的第一项和最后一项之间的时间差,而不管事件文本的如何。因此,您可以自联接表以获取所有项,然后根据ID对该项进行分组,获得该项的最小和最大时间。
select
CompleteEvents.EventID
,min(AllEvents.EventTime) first_event
,max(AllEvents.EventTime) last_event
,datediff(s, min(AllEvents.EventTime), max(AllEvents.EventTime)) seconds_difference
from Events CompleteEvents
inner join Events AllEvents on
AllEvents.EventID = CompleteEvents.EventID
where
upper(CompleteEvents.EventText) like '%COMPLETE%'
group by CompleteEvents.EventID查看同一查询的这个SQL Fiddle。
发布于 2018-07-02 16:32:33
我会把这件事当作:
SELECT id, DATEDIFF(seconds, MIN(time), MAX(time)) as num_seconds
FROM eventtable
GROUP BY id
HAVING SUM(CASE WHEN e.event = 'complete' THEN 1 ELSE 0 END); https://stackoverflow.com/questions/51139427
复制相似问题