SQL-总和列,直到其他列条件为止

时间:2018-06-26 16:25:11

标签: sql

我有一个包含三列的表:

employee_iddayssales

employee_id不是唯一的,因为它会重复不同的天数和销售额组合。

我想生成一个包含三列的表:

employee_idsales - 30sales - final

其中:

employee_id现在是唯一的

sales - 30 =总和(销售额)(其中天<= 30),并且

sales - final =每个ID的总和(销售额)。

这是我要查找的之前/之后的内容。任何帮助将不胜感激!

示例图片在下面链接!

before image

after image

4 个答案:

答案 0 :(得分:4)

您可以使用conditional aggregation

select employee_id,
       sum(case when days <= 30 then sales end) as sales30,
       sum(sales) as allsales
from yourtable
group by employee_id

答案 1 :(得分:1)

        Select empid , sum (sales)  as total ,
         sum (case when days <=30 then sales else 0 end ) as sales_30 
        from SALES_DATA 
         GROUP BY empid 

答案 2 :(得分:0)

        Select empid , sum (sales)  as total ,
         sum (case when days <=30 then sales  
        else 0 end ) as sales_30 
        from SALES_DATA 
         GROUP BY empid 

答案 3 :(得分:0)

在Oracle中,您可以尝试

与sale30 AS(SELECT employee_id,SUM(sale)销售 WHERE天<= 30 GROUP BY employee_id), saleFinal AS(SELECT employee_id,SUM(sale)销售 GROUP BY employee_id) SELECT sf.employee_id,s3.sale sale_30,sf.sale 从salefinal sf,sale30 s3 哪里sf.employee_id = s3.employee_id(+)

通常您可以使用

SELECT sf.employee_id,s3.sale sale_30,sf.sale FROM(选择employee_id,SUM(sale)销售 GROUP BY employee_id)sf,(SELECT employee_id,SUM(sale)sale WHERE day <= 30 GROUP BY employee_id)s3 哪里sf.employee_id = s3.employee_id(+)