对某些分组行求和

时间:2018-08-28 18:27:14

标签: sql presto

我有一个数据集,显示了每个类别的消费者(来过一次,两次,3次,4次,5次等的消费者)的来宾数量和收入。

它看起来像这样: enter image description here

我要获取上述表格的查询是:

SELECT number_of_trans, COUNT(*) AS guest_count, SUM(amount) AS revenue FROM customer_counting GROUP BY number_of_trans ORDER BY number_of_trans

现在,我想将guest_count和收入加起来,并想将它们归为以下类别:1、2、3、4、5-7和8 +。

所以实际上1,2,3和4将保持不变,但我将在第5-7行以及第8行及以后的行中求和。

我该怎么做?我想要的表如下(不用担心值的准确性):

enter image description here

我希望我的问题得到理解。

2 个答案:

答案 0 :(得分:1)

使用case和一个子查询(或CTE):

SELECT (CASE WHEN number_of_trans < 5 THEN CAST(number_of_trans as varchar)
             WHEN number_of_trans < 8 THEN '5-7'
             ELSE '8+'
        END) as grp,
       SUM(guest_count) as guest_count, SUM(revenue) as revenue
FROM (SELECT number_of_trans, COUNT(*) AS guest_count, SUM(amount) AS revenue
      FROM customer_counting
      GROUP BY number_of_trans
     ) x
GROUP BY grp
ORDER BY MIN(number_of_trans);

答案 1 :(得分:0)

戈登提案的简单形式:

SELECT 
  CASE WHEN number_of_trans < 5 THEN cast(number_of_trans as varchar)
    WHEN number_of_trans < 8 THEN '5-7'
    ELSE '8+' 
  END as freq_band, 
  COUNT(*) AS guest_count, 
  SUM(amount) AS revenue 
FROM customer_counting 
GROUP BY CASE WHEN number_of_trans < 5 THEN cast(number_of_trans as varchar)
    WHEN number_of_trans < 8 THEN '5-7'
    ELSE '8+' 
  END
ORDER BY freq_band