我想获得过去三年内提出请求的所有用户列表。
请求(request_id,request_day,user_id,userprofile_id)
我做得对吗?
SELECT user_id
FROM requests
WHERE EXTRACT(YEAR FROM request_day) IN ( 2014,2015,2016 )
GROUP BY user_id
HAVING COUNT(*) = 3;
答案 0 :(得分:2)
您当前的方法几乎正确。您需要做的就是按 distinct 年数来计算:
SELECT user_id
FROM requests
WHERE YEAR(request_day) IN (2014, 2015, 2016)
GROUP BY user_id
HAVING COUNT(DISTINCT YEAR(request_day)) = 3;
如果DISTINCT
年数为3,则表示用户在WHERE IN
子句中拥有所有三年。
请注意,执行此操作的另一种方法是条件聚合:
SELECT user_id
FROM requests
GROUP BY user_id
HAVING SUM(CASE WHEN YEAR(request_day) = 2014 THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN YEAR(request_day) = 2015 THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN YEAR(request_day) = 2016 THEN 1 ELSE 0 END) > 0
如果您的查询变得更复杂,这种方法可以更好地扩展。