与前一天相差5天的日期计数

时间:2013-08-28 15:24:15

标签: mysql sql

我有一张包含日期和用户的表格。我需要帮助,试图弄清楚如何只统计上一个日期后5天的日期。

id|users_id|date
--------------------------------
1 | 1      | 2013-08-01 00:00:00
2 | 2      | 2013-08-03 00:00:00
3 | 1      | 2013-08-04 00:00:00
4 | 1      | 2013-08-06 00:00:00
5 | 2      | 2013-08-06 00:00:00
6 | 2      | 2013-08-10 00:00:00
7 | 2      | 2013-08-11 00:00:00

通过以下示例,我应该为用户1获得2,为用户2获得2.我尝试做一个子查询,但是我无法传递时间戳来进行比较。任何帮助将非常感激。谢谢。

以下是我的一些示例查询。

SELECT 
    tbl1.users_id,
    COUNT(tbl2.date)
FROM table tbl1
LEFT JOIN table tbl2 
    ON tbl2.users_id = tbl1.users_id 
    AND tbl2.date > DATE_ADD(tbl1.date, INTERVAL 5 DAY)
GROUP BY tbl1.users_id;

SELECT 
    tbl1.users_id,
    COUNT(tbl2.date)
FROM table tbl1
LEFT JOIN (
    SELECT users_id, date
    FROM table
    WHERE date > DATE_ADD(tbl1.date, INTERVAL 5 DAY)
) tbl2 ON tbl1.users_id = tbl1.users_id
GROUP BY tbl1.users_id;

最后一种方法显然不起作用,因为我不能将tbl1的日期放在子查询中。

1 个答案:

答案 0 :(得分:1)

未经测试,但这样的事情可能: -

SELECT tbl1.users_id, COUNT(tbl2.date)
FROM (SELECT users_id, date, @Counter:=IF(users_id = @PrevId, @Counter + 1, 1) AS SequenceCtr, @PrevId:=users_id
FROM atable
CROSS JOIN (SELECT @Counter:=0, @PrevId:=0) Sub1
ORDER BY users_id, date) AS tbl1
LEFT OUTER JOIN (SELECT users_id, date, @Counter:=IF(users_id = @PrevId, @Counter + 1, 1) AS SequenceCtr, @PrevId:=users_id
FROM atable
CROSS JOIN (SELECT @Counter:=0, @PrevId:=0) Sub1
ORDER BY users_id, date) AS tbl2
ON tbl1.users_id = tbl2.users_id
AND tbl1.SequenceCtr + 1 = tbl2.SequenceCtr
AND tbl2.date > DATE_ADD(tbl1.date, INTERVAL 5 DAY)
GROUP BY tbl1.users_id;

一些子选择来获取日期列表但添加了序列号。然后按照你的方式加入,但也加入序列号为1的不同。

编辑 - 对SQL小提琴进行了快速测试,似乎有效: -

http://sqlfiddle.com/#!2/6c69b/1