0

我有一个表,其中包含多个事件类型的多行。

每个开始事件都有一个结束事件。由于设计选择,开始事件在列中具有结束事件的 ID,但反之则不然。同样,开始原因与结束原因不同。

我的专栏是:

eventTYPE - the type of event (start, end, terminate etc)
eventID - unique ID
eventDate - date the event will happen
endEvent - ID of end event (if event type <> start - this will be NULL)
reason - Reason for the event

我需要在用户指定的日期返回所有比较 eventType=START 的 eventType=END 的原因不是出于某种原因。

我知道我需要使用以下三个语句,但我不确定如何组合它们。

SELECT eventId 
FROM Events
WHERE eventType='END' and eventDate='<USER SPECIFIED>'

SELECT endEvent    
FROM Events
WHERE eventType='START' and reason <> 'mgp' and endEvent='<ID FROM ABOVE>'

SELECT * 
FROM dbo.Events 
WHERE eventType='END' and eventId='<END EVENT FROM ABOVE>'

任何帮助表示赞赏!

4

2 回答 2

2

查询是这样的:

select *
from events se left outer join
     events ee
     on se.endevent = ee.eventid and se.eventtype = 'start' and ee.eventtype = 'end'
where ee.eventdate = '<USER SPECIFIED>' and
       se.reason <> 'mgp'

这只是将事件连接在一起,匹配开始和结束记录,然后将逻辑应用于该结果。

于 2013-02-15T01:13:33.727 回答
0

怎么样,

SELECT * 
FROM dbo.Events 
WHERE eventType='END' and eventId IN (

   SELECT endEvent    
   FROM Events
   WHERE eventType='START' and reason <> 'mgp' and endEvent IN (

      SELECT eventId 
      FROM Events
      WHERE eventType='END' and eventDate='<USER SPECIFIED>'

   )
)
于 2013-02-15T01:13:09.700 回答