如何建立MySQL查询,如果有'if'并检查下一行是否存在值?

时间:2019-04-02 21:42:01

标签: mysql

我有桌子:

RecordID Date        Time  EventID UserID ClientID
1       |2019-02-01 |15:00 |2       |100   |5
2       |2019-02-01 |17:00 |2       |150   |5
3       |2019-02-05 |12:00 |2       |200   |5
4       |2019-02-05 |15:00 |3       |100   |5
5       |2019-02-06 |15:00 |2       |200   |5

我需要编写查询以获取每个用户与Client合作的天数。

<-伪代码->

foreach row 
  Date = date, EventId = eid, ClientId = cid
  if(in table exists anotherRow with EventId=eid and ClientId=cid){
    DateStart = date, DateEnd = anotherRow (Date),Days=DateEnd-DateStart
  }else{ DateStart = date, DateEnd = NOW(), Days=DateEnd-DateStart}

<-/////////////////-->

输出应如下所示:

UserID DateStart DateEnd     Days EventId ClientId
100 |2019-02-01 |2019-02-01 |1    |        |
150 |2019-02-01 |2019-02-05 |5    |        | 
200 |2019-02-05 |2019-02-06 |2    |        |

1 个答案:

答案 0 :(得分:0)

这是我的查询:

选择

  RecordId AS RecId, Date, Time, EventId AS EvID, UserId,
    CASE
      WHEN (LEAD(EventId) OVER W = EventId)
        THEN (LEAD(Date) OVER W - Date + 1)
      WHEN (LEAD(EventId) OVER W != EventId AND (SELECT Date FROM first WHERE (RecordId > RecId AND EvID = EventId) LIMIT 1))
        THEN DATEDIFF((SELECT Date FROM first WHERE (RecordId > RecId AND EvID = EventId) LIMIT 1), Date) + 1
      ELSE DATEDIFF(Date, NOW())
    END
AS 'diff'   FROM first WINDOW W AS (ORDER BY Date);