3

我的表包含日期、用户、用户位置,例如:

20120417 userA location1
20120417  userA location2
20120417  userB location3
20120417  userC location2
20120417  userA location1
20120417  userB location2
20120417 userA location3
20120416 userA location1
20120416  userA location2
20120416  userB location3
20120416  userC location2
20120416  userA location1
20120416  userB location2
20120415 userA location3
20120415 userA location1
20120415  userA location2
20120415  userB location3
20120415  userC location2
20120415  userA location1
20120415  userB location2
20120415 userA location3
20120414 ....
....

我尝试了几种愚蠢的方法来找到连续 3 天匹配的用户,每天必须至少有 2 个不同的位置。

是否可以使用 sql 查询来执行此操作,或者我应该尝试使用 php 脚本之类的东西?

4

1 回答 1

0

我认为这行得通。使用 MSSQL,无需复制派生表。

SELECT l1.user,l1.thedate, COUNT(*) CNT FROM
( /* Derived table1: user,thedate,loc */
SELECT st.user,st.thedate,COUNT(*) locs FROM sotest st
GROUP BY st.user,st.thedate 
HAVING( COUNT(DISTINCT st.location) > 1)
) l1
JOIN
( /* Derived table2: user,thedate,loc */
SELECT st.user,st.thedate,COUNT(*) locs FROM sotest st
GROUP BY st.user,st.thedate 
HAVING( COUNT(DISTINCT st.location) > 1)
) l2 ON l2.user = l1.user and DATEDIFF(l2.thedate , l1.thedate) = 1
JOIN
( /* Derived table3: user,thedate,loc */
SELECT st.user,st.thedate,COUNT(*) locs FROM sotest st
GROUP BY st.user,st.thedate 
HAVING( COUNT(DISTINCT st.location) > 1)
) l3  ON l3.user = l2.user and DATEDIFF(l3.thedate , l2.thedate) = 1
GROUP BY l1.user,l1.thedate

每个派生表都标识了用户拥有 2 个或更多位置的那些日子。

于 2015-03-06T21:21:40.097 回答