我有以下查询。我想调整以仅选择具有多个subscription_plans的user_id。例如,如果user_id 4只有一个subscription_plan_id,则他不应该出现。
如果user_id 5的subscription_plan_id为2和3,他应该出现。关于如何做到这一点的任何建议?
select user_id, subscription_plan_id, created_at from
subscriptions where
(subscription_plan_id = 47 or
subscription_plan_id = 78)
and created_at between '2014-01-01' and '2014-01-31';
答案 0 :(得分:2)
查看这些SQL关键字:
好的,好的,我会为你做的...... [抱怨] ....
SELECT
user_id, COUNT(DISTINCT subscription_plan_id), MIN(created_at), MAX(created_at)
FROM
subscriptions
WHERE
created_at BETWEEN '2014-01-01' AND '2014-01-31'
GROUP BY
user_id
HAVING
COUNT(DISTINCT subscription_plan_id) > 1
;
答案 1 :(得分:0)
您需要使用GROUP BY
和HAVING
来过滤掉具有少量订阅的用户,在您的情况下小于1。
试试这样的事情
select user_id, subscription_plan_id, created_at
from subscriptions
where (subscription_plan_id = 47 or
subscription_plan_id = 78)
and created_at between '2014-01-01' and '2014-01-31'
AND user_id IN (SELECT user_id FROM subscriptions ss
GROUP BY ss.user_id
HAVING COUNT(subscription_plan_id) > 1) ;