首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我希望在sql中为值的平均值构建一个case语句。

我希望在sql中为值的平均值构建一个case语句。
EN

Stack Overflow用户
提问于 2022-01-11 06:29:38
回答 1查看 63关注 0票数 0

我有一组客户的数据,订单的数量和订单的价值。我试图根据客户的平均订单价值将数据分成5段。

代码语言:javascript
复制
select case
         when avg(total_amount) <= 3.5 then
          '<3.5'
         when avg(total_amount) > 3.5 and avg(total_amount) <= 4.5 then
          ' 3.5-4.5'
         when avg(total_amount) > 4.5 and avg(total_amount) <= 6 then
          ' 4.5-6'
         when avg(total_amount) > 6 and avg(total_amount) <= 8 then
          '6-8'
         else
          'over 8'
       end as bucket,
       count(customer_id),
       avg(total_amount),
       avg(order_count)
  from (select customer_account_id,
               sum(spent amount) as total_amount,
               count(order_id) as order_count
          from data_table
         group by customer_account_id)
 group by bucket;

我只想要5行输出,显示每个桶中的花费和订单。

EN

回答 1

Stack Overflow用户

发布于 2022-01-11 09:22:11

您可以尝试这样的方法(未经测试):

代码语言:javascript
复制
WITH list AS
( SELECT customer_account_id as customer_id,
         sum(spent_amount) as total_amount,
         count(order_id) as order_count
    FROM data_table
   GROUP BY customer_account_id
)
SELECT CASE
         when range = numrange (0, 3.5, '[]') then '<3.5'
         when range = numrange (3.5, 4.5, '(]') then '3.5-4.5'
         when range = numrange (4.5, 6.0, '(]') then '4.5-6'
         when range = numrange (6.0, 8.0, '(]') then '6-8'
         else 'over 8'
       END AS bucket,
       count(customer_id),
       avg(total_amount),
       avg(order_count)
  FROM list
 INNER JOIN (VALUES (numrange (0, 3.5, '[]')),(numrange (3.5, 4.5, '(]')),(numrange (4.5, 6.0, '(]')),(numrange (6.0, 8.0, '(]')),(numrange (8.0, NULL, '(]'))) AS range
    ON range @> total_amount
 GROUP BY range
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70662472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档