我需要选择自数据中断以来的天数。它更容易显示:
表格式:
id (autoincrement), user_id (int), start (datetime), end (datetime)
示例数据(仅剩下需要几天的时间):
1, 5, 2011-12-18, 2011-12-18
2, 5, 2011-12-17, 2011-12-17
3, 5, 2011-12-16, 2011-12-16
4, 5, 2011-12-13, 2011-12-13
正如您所看到的,2011-12-13和2011-12-16之间会有一个休息时间。现在,我需要说:
使用日期2011-12-18,在休息之前有多少天:
2011-12-18: Lowest sequential date = 2011-12-16: Total consecutive days: 3
可能:DATE_DIFF(2011-12-18, 2011-12-16)
所以我的问题是,如何选择2011-12-16是最低的连续日期?请记住,数据适用于特定的user_id
。
这有点像这里的例子:http://www.artfulsoftware.com/infotree/queries.php#72但反过来。
我只想在SQL中完成,没有php代码
由于
答案 0 :(得分:0)
SELECT qmin.start, qmax.end, DATE_DIFF( qmax.end, qmin.start ) FROM table AS qmin
LEFT JOIN (
SELECT end FROM table AS t1
LEFT JOIN table AS t2 ON
t2.start > t1.end AND
t2.start < DATE_ADD( t1.end, 1 DAY )
WHERE t1.end >= '2011-12-18' AND t2.start IS NULL
ORDER BY end ASC LIMIT 1
) AS qmax
LEFT JOIN table AS t2 ON
t2.end < qmin.start AND
t2.end > DATE_DIFF( qmin.start, 1 DAY )
WHERE qmin.start <= '2011-12-18' AND t2.start IS NULL
ORDER BY end DESC LIMIT 1
这应该可以工作 - 左连接选择一个可以按顺序排列的日期,因此如果你在没有连续记录的情况下获取最近的记录(t2.anyfield为空),则可以将最大限度删除,与最小日期相同。< / p>
如果你可以计算脚本之间的天数 - 使用联合做(例如1.行 - 最小,2行最大)
答案 1 :(得分:0)
如果它不是美容内容,那么您可以尝试以下方式:
select t.start, t2.start, datediff(t2.start, t.start) + 1 as consecutive_days
from tab t
join tab t2 on t2.start = (select min(start) from (
select c1.*, case when c2.id is null then 1 else 0 end as gap
from tab c1
left join tab c2 on c1.start = adddate(c2.start, -1)
) t4 where t4.start <= t.start and t4.start >= (select max(start) from (
select c1.*, case when c2.id is null then 1 else 0 end as gap
from tab c1
left join tab c2 on c1.start = adddate(c2.start, -1)
) t3 where t3.start <= t.start and t3.gap = 1))
where t.start = '2011-12-18'
结果应该是:
start start consecutive_days
2011-12-18 2011-12-16 3
答案 2 :(得分:0)
检查一下,
SELECT DATEDIFF((SELECT MAX(`start`) FROM testtbl WHERE `user_id`=1),
(select a.`start` from testtbl as a
left outer join testtbl as b on a.user_id = b.user_id
AND a.`start` = b.`start` + INTERVAL 1 DAY
where a.user_id=1 AND b.`start` is null
ORDER BY a.`start` desc LIMIT 1))
DATEDIFF()显示两天的差异,如果您想连续几天为该结果添加一个。