&
技术问答
250 人阅读
|
0 人回复
|
2023-09-14
|
created_at (DATETIME)我想找用户连续几天访问我们的应用程序。因此,例如:5 N1 H2 W& n0 i! ]5 e4 n) z& m
SELECT DISTINCT DATE(created_at) AS d FROM visits WHERE uid = 123将返回:
, G8 G; ]2 k( l% t) Q d ------------ 2012-04-28 2012-04-29 2012-04-30 2012-05-03 2012-05-04五个记录和两个间隔-3天(4月28日至30日)和2天(5月3日至4日)。
4 {; \8 j8 ]8 Q' C: v$ T4 @5 K我的问题是如何找到用户连续访问应用程序的最大天数(例如为3天)。SQL在文档中找到合适的函数,但没有成功。我想念什么?/ y* Y# N: W, d) N
UPD:
V% L }! L4 J. ` p谢谢你的回答!其实我在用vertica分析数据库(http://vertica.com/),但这是一个非常罕见的解决方案,只有少数人有使用它的经验。尽管它支持它SQL-99标准。' X* }4 \! b, W$ J9 `
大多数解决方案都需要稍加修改。最后,我创建了自己的查询版本:
+ H D2 ^4 ~/ U5 h+ U-- returns starts of the vitit series SELECT t1.d as s FROM testing t1LEFT JOIN testing t2 ON DATE(t2.d) = DATE(TIMESTAMPADD('day',-1,t1.d))WHERE t2.d is null GROUP BY t1.d s --------------------- 2012-04-28 01:00:00 2012-05-03 01:00:00-- returns end of the vitit series SELECT t1.d as f FROM testing t1LEFT JOIN testing t2 ON DATE(t2.d) = DATE(TIMESTAMPADD('day',1,t1.d))WHERE t2.d is null GROUP BY t1.d f --------------------- 2012-04-30 01:00:00 2012-05-04 01:00:00因此,我们现在唯一需要做的就是以某种方式连接它们,比如通过行索引。$ y3 o. h+ h9 k- r
SELECT s,f,DATEDIFF(day,s,f) 1 as seq FROM ( SELECT t1.d as s,ROW_NUMBER() OVER () as o1 FROM testing t1 LEFT JOIN testing t2 ON DATE(t2.d) = DATE(TIMESTAMPADD('day',-1,t1.d)) WHERE t2.d is null GROUP BY t1.d) tbl1 LEFT JOIN ( SELECT t1.d as f,ROW_NUMBER() OVER () as o2 FROM testing t1 LEFT JOIN testing t2 ON DATE(t2.d) = DATE(TIMESTAMPADD('day',1,t1.d)) WHERE t2.d is null GROUP BY t1.d) tbl2 ON o1 = o2样本输出:
% H L$ `6 K! W s |
|
|
|
|
|