找到在MySQL中重复和匹配条件的用户

时间:2012-04-16 19:53:25

标签: php mysql

我的表包含date,user,user_location,如:

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脚本的内容?

1 个答案:

答案 0 :(得分: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个或更多位置的那些日子。