如何构建mysql查询,使用'if'并检查下一行中是否存在值?

问题描述 投票:0回答:1

我有桌子:

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    |        |
mysql
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.