按求和变量分组

kh212irz  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(375)
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

但是,如果bob在周一存款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

思想?

syqv5f0l

syqv5f0l1#

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

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
zz2j4svz

zz2j4svz2#

将分组更改为“基于用户”,并对所有发生的存款进行合计。然后计算每一笔存款的用户数:

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

相关问题