按汇总变量分组

时间:2016-10-05 21:32:57

标签: mysql group-by sum distinct

SELECT deposit.numberSuccessfulDeposits, count(distinct userid) 
FROM deposit WHERE deposit.asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59'
AND deposit.licenseeId = 1306
GROUP BY deposit.numberSuccessfulDeposits

示例输出

numberSuccessfulDeposits     count(distinct userid) 
 0   228 
 1   878 
 2   90 
 3   37 
 4   17 

然而,如果鲍勃在周一进行了1次存款而在周二进行了3次存款,那么它将计入" 1"和" 3"成功存款的数量。

numberSuccessfulDeposits     count(distinct userid) 
 0   ## 
 1   1 
 2   ## 
 3   1 
 4   ## 

理想情况下,它应该只计入" 4"

numberSuccessfulDeposits     count(distinct userid) 
 0   ## 
 1   ## 
 2   ## 
 3   ## 
 4   1

思想?

2 个答案:

答案 0 :(得分:1)

将分组更改为基于用户并将所有存款的总和相加。然后计算用户每笔存款的总和:

SELECT
  numberSuccessfulDeposits,
  COUNT(userid) AS users_count
FROM (
  SELECT 
    sum(numberSuccessfulDeposits) AS numberSuccessfulDeposits, 
    userid
  FROM deposit
  WHERE asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59'
    AND licenseeId = 1306
  GROUP BY userid
  ) t
GROUP BY numberSuccessfulDeposits

编辑:将处理分组为0,1,2,3 +类别看起来像这样:

SELECT
  numberSuccessfulDeposits,
  COUNT(userid) AS user_count
FROM (
  SELECT
    CASE WHEN numberSuccessfulDeposits >= 3 THEN '3+' ELSE numberSuccessfulDeposits::TEXT END AS numberSuccessfulDeposits,
    userid
  FROM (
    SELECT 
      sum(numberSuccessfulDeposits) AS numberSuccessfulDeposits, 
      userid
    FROM deposit
    WHERE asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59'
      AND licenseeId = 1306
    GROUP BY userid
    ) t
  ) f
GROUP BY numberSuccessfulDeposits

答案 1 :(得分:0)

计算子查询中的每用户总和,然后计算主查询中的每总计数。

SELECT totalDeposits, COUNT(*)
FROM (SELECT userid, SUM(numberOfSuccessfulDeposits) AS totalDeposits
      FROM deposit 
      WHERE deposit.asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59'
      AND deposit.licenseeId = 1306
      GROUP BY userid) AS subquery
GROUP BY totalDeposits