0

我有一张包含日期和用户的表格。我需要帮助来弄清楚如何仅计算前一个日期后 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 的日期放在子查询中。

4

1 回答 1

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;

几个子选择来获取日期列表,但添加了一个序列号。然后像你一样加入,但也加入序列号不同的地方。

编辑 - 对 SQL fiddle 进行了快速测试,它似乎有效: -

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

于 2013-08-28T16:03:51.130 回答