【问题标题】:How to aggregate by each level level in a case study in SQL?如何在 SQL 案例研究中按每个级别级别聚合?
【发布时间】:2020-12-31 15:49:03
【问题描述】:
select 
Count(CASE
    WHEN quantity * saleprice <= 400 THEN 'B'
    WHEN quantity * saleprice between 400 and 999 THEN 'S'
    WHEN quantity * saleprice between 1000 and 2099 THEN 'G'
    WHEN quantity * saleprice >=2100 THEN 'D' END) AS Level,
   c.customerid CountOfCustomers
from customers c join sales s on c.customerid = s.customerid join saleitem si on s.saleid = si.saleid
group by c.customerid

我需要按此 Case 语句中的每个级别进行聚合,但是当我将整个 case 语句放在 group by 子句中时,我只能得到一行输出。

【问题讨论】:

  • 请提供样本数据和期望的结果。不清楚您所说的“按每个级别汇总”是什么意思。

标签: sql group-by count sum case


【解决方案1】:

我怀疑您想要两个级别的聚合:首先根据客户的总销售额将客户放入存储桶,然后计算每个存储桶的客户:

select lvl, count(*) cnt_customers
from (
    select case 
        when sum(quantity * saleprice) <   400 then 'B'
        when sum(quantity * saleprice) <  1000 then 'S'
        when sum(quantity * saleprice) <  2100 then 'G'
        when sum(quantity * saleprice) >= 2100 then 'D'
    end as lvl
    from customers c 
    inner join sales s on c.customerid = s.customerid 
    inner join saleitem si on s.saleid = si.saleid
    group by c.customerid
) t
group by lvl

【讨论】:

  • 谢谢!你能解释一下你使用的内连接吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
相关资源
最近更新 更多