如何只选择那些附加了多个记录的用户?

时间:2014-05-02 15:50:28

标签: sql

我有以下查询。我想调整以仅选择具有多个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';

2 个答案:

答案 0 :(得分:2)

查看这些SQL关键字:

  • GROUP BY
  • HAVING
  • COUNT(DISTINCT [column])

好的,好的,我会为你做的...... [抱怨] ....

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 BYHAVING来过滤掉具有少量订阅的用户,在您的情况下小于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)  ;