我正在尝试构建一个查询,该查询将列出在过去90天内但在最近30天内没有条目的表中的所有用户ID。
该表的超简化版本将包含三个字段:RecordID(主键,自动增量),UserID(外键)和RecordDate(时间戳)。
我知道如何在两个查询中执行此操作,但可以在一个查询中完成吗?它应该为任何条目少于90天的用户返回userid,但在过去30天内没有条目。
答案 0 :(得分:0)
select distinct(userid)
from thetable
where recorddate > DATE_SUB(now(), INTERVAL 90 DAY)
and userid not in
(
select userid
from thetable
where recorddate > DATE_SUB(now(), INTERVAL 30 DAY)
)
我不太了解mySQL,所以请使用适当的方法检查日期是否在过去的x天内
我假设用户标识可以多次出现在表中,但您只希望它们返回一次。因此“不同”
答案 1 :(得分:0)
以下查询应该完成这项工作:
SELECT UserID
FROM MyTable AS T1
WHERE
(SELECT MIN(DATEDIFF(NOW(),RecordDate))
FROM MyTable AS T2 -- Most recent entry must be more
WHERE T2.UserID=T1.UserId) BETWEEN 31 AND 90 -- than 30 days ago, but no more
-- than 90 days ago
答案 2 :(得分:0)
这应该这样做
SELECT DISTINCT UserID
FROM Table t1
WHERE RecordDate > DATE_SUB(NOW(), INTERVAL 90 DAY)
AND NOT EXISTS (
SELECT 1 FROM Table
WHERE RecordDate > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND UserID = t1.UserID
)
答案 3 :(得分:0)
SELECT UserID
FROM
(
SELECT UserID,
MIN(RecordDate) AS min_date,
MAX(RecordDate) AS max_date
FROM MyTable
GROUP BY UserID
)
WHERE max_date < AddDate(CURRENT_TIMESTAMP, INTERVAL -30 DAY)
AND min_date >= AddDate(CURRENT_TIMESTAMP, INTERVAL -90 DAY)