如何在sql中选择具有多个值的记录?

时间:2014-05-02 16:47:52

标签: sql

以下代码返回具有多个的给定用户的subscription_plan_ids计数。但是,我希望它返回实际的subscription_plan_ids而不仅仅是count。

Example:
user_id,subscription_plan_id
1,1
1,3


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 :(得分:0)

要在一行中返回所有订阅计划ID,请使用GROUP_CONCAT:

SELECT user_id, GROUP_CONCAT(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

要将它们分成多行:

SELECT DISTINCT user_id, subscription_plan_id, created_at
FROM subscriptions s
WHERE user_id IN (
    SELECT user_id
    FROM subscriptions
    WHERE 
      created_at BETWEEN '2014-01-01' AND '2014-01-31'
    GROUP BY
      user_id
    HAVING
      COUNT(DISTINCT subscription_plan_id) > 1)
AND created_at BETWEEN '2014-01-01' AND '2014-01-31'
ORDER BY user_id, created_at