Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL的案例研究中按每个级别进行聚合?_Sql_Group By_Count_Sum_Case - Fatal编程技术网

如何在SQL的案例研究中按每个级别进行聚合?

如何在SQL的案例研究中按每个级别进行聚合?,sql,group-by,count,sum,case,Sql,Group By,Count,Sum,Case,在这个Case语句中,我需要按每个级别进行聚合,但是当我将整个Case语句放入group by子句中时,我只得到一行输出。我怀疑您需要两个级别的聚合:首先根据客户的总销售额将客户放入存储桶中,然后计算每个存储桶中的客户数: select Count(CASE WHEN quantity * saleprice <= 400 THEN 'B' WHEN quantity * saleprice between 400 and 999 THEN 'S' WHEN qu

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

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

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

请提供样本数据和预期结果。现在还不清楚你所说的每个级别的聚合是什么意思。谢谢!你能解释一下你使用的内部连接吗?
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