按用户分组选择5个连续日期的记录

时间:2018-09-04 08:02:33

标签: mysql sql database

我具有以下表结构,我只想要连续5个日期中的记录并按uid分组。

这是我的数据结构

user_master

uid | name
1   |  A
2   |  B
3   |  C
4   |  D

tbl_referral

refId   |  uid  |   Date
1       |  1    |   01-09-2018
2       |  1    |   02-09-2018
3       |  1    |   03-09-2018
4       |  2    |   01-09-2018
5       |  2    |   02-09-2018
6       |  1    |   04-09-2018
7       |  2    |   05-09-2018
8       |  2    |   06-09-2018
9       |  1    |   05-09-2018
10      |  2    |   06-09-2018

现在,我只想从tbl_referral中获取日期连续出现5次的记录

必需的输出

uid | Date
    | 01-09-2018
    | 02-09-2018
1   | 03-09-2018
    | 04-09-2018
    | 05-09-2018

2 个答案:

答案 0 :(得分:5)

您可以将表与自身连接起来,并计算5天范围内的行数。如果计数为5,则该范围包含所有连续的日期。

SELECT t1.uid, GROUP_CONCAT(t2.Date) AS dates
FROM tbl_referral AS t1
JOIN tbl_referral AS t2 ON t1.uid = t2.uid AND t2.date BETWEEN t1.date AND DATE_ADD(t1.date, INTERVAL 4 DAY)
GROUP BY t1.uid, t1.date
HAVING COUNT(*) = 5

此查询假定date列的数据类型为DATE,而不是字符串。如果是字符串,则需要使用STR_TO_DATE()将其转换为日期,如Nick的回答。但是最好将日期存储为DATE而不是字符串,这样就可以利用索引(它们也占用更少的空间)。

答案 1 :(得分:1)

您可以通过将表自身连接4次来完成此操作,此后每一天一次。请注意,由于您的日期不是MySQL格式,因此必须将其转换为数学形式:

SELECT t1.uid, CONCAT_WS(',', t1.Date, t2.Date, t3.Date, t4.Date, t5.Date) AS Dates
FROM tbl_referral t1
JOIN tbl_referral t2 ON t2.uid = t1.uid AND
  STR_TO_DATE(t2.Date, '%d-%m-%Y') = STR_TO_DATE(t1.Date, '%d-%m-%Y') + INTERVAL 1 DAY
JOIN tbl_referral t3 ON t3.uid = t2.uid AND
  STR_TO_DATE(t3.Date, '%d-%m-%Y') = STR_TO_DATE(t2.Date, '%d-%m-%Y') + INTERVAL 1 DAY
JOIN tbl_referral t4 ON t4.uid = t3.uid AND
  STR_TO_DATE(t4.Date, '%d-%m-%Y') = STR_TO_DATE(t3.Date, '%d-%m-%Y') + INTERVAL 1 DAY
JOIN tbl_referral t5 ON t5.uid = t4.uid AND
  STR_TO_DATE(t5.Date, '%d-%m-%Y') = STR_TO_DATE(t4.Date, '%d-%m-%Y') + INTERVAL 1 DAY

输出:

uid     Dates
1       01-09-2018,02-09-2018,03-09-2018,04-09-2018,05-09-2018

SQLFiddle Demo