SELECT * FROM Table1 t1
WHERE t1.referring_url <> 'site.com'
AND EXISTS (
SELECT * FROM Table1 ex
WHERE ex.user_id = t1.user_id
AND ex.referring_url <> 'site.com'
AND ex.stamp < t1.stamp
);
顺便说一句:我重命名datetime
为stamp
,因为它是保留字。
更新:如果您只对价格感兴趣,您可以这样做;
SELECT t1.user_id, COUNT(*) AS reet
FROM Table1 t1
WHERE t1.referring_url <> 'site.com'
AND EXISTS (
SELECT * FROM Table1 ex
WHERE ex.user_id = t1.user_id
AND ex.referring_url <> 'site.com'
AND ex.stamp < t1.stamp
)
GROUP BY t1.user_id
;
更新:如果您希望用户的重复次数为零,则可以在 CTE(或子查询)上使用连接:
WITH cnt AS (
SELECT tx.user_id , COUNT(*) AS cnt
FROM Table1 tx
WHERE tx.referring_url <> 'site.com'
AND EXISTS (
SELECT * FROM Table1 ex
WHERE ex.user_id = tx.user_id
AND ex.referring_url <> 'site.com'
AND ex.stamp < tx.stamp
)
GROUP BY tx.user_id
)
SELECT DISTINCT t1.user_id
, COALESCE(cnt.cnt, 0) AS reet
FROM Table1 t1
LEFT JOIN cnt ON cnt.user_id = t1.user_id
;