【问题标题】:Subtraction of values based on IDs and group after基于 ID 和分组后的值减法
【发布时间】:2015-05-08 06:21:47
【问题描述】:

我正在使用 Oracle。

有一个表:

Year   Type   Value
2011   1       500
2011   2       550
2011   3       600
...
...
2012   1       600
2012   2       750
2012   3       930

我需要减去按年份分组的不同类型的所有值。 操作将是:

2011 年 -> 1-2-3 (500-550-600)

2012 年 -> 1-2-3 (600-750-930)

为了……

结果应该是:

Year   Value
2011   -650  
2012   -1080 
...    ...  

我只是无法让这个查询正常工作..

【问题讨论】:

    标签: sql oracle group-by subtraction


    【解决方案1】:

    使用条件聚合:

    select sum(case when type = 1 then value else - value end) as value
    from table t
    group by year;
    

    【讨论】:

    • 更好的解决方案(+1)!
    • @sgeddes 。 . .你的解决方案很合理。 . .尽管可以通过 end 来改进它,所以它在语法上是正确的。 ;)
    • 工作就像一个魅力!谢谢!
    【解决方案2】:

    您的意思是 GROUP BY,CASE 决定符号 + 代表类型 1,- 代表其他:

    select "year", 
           SUM(case when type = 1 then value else -value end)
    from yourtable
    group by "year"
    

    【讨论】:

    • 糟糕。我这里有点慢......(直到现在才注意到Gordon Linoff的回答。)
    猜你喜欢
    • 2018-09-21
    • 2020-03-03
    • 2021-09-10
    • 2014-05-08
    • 1970-01-01
    • 2020-11-10
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多