SQL 条件聚合
SQL Conditional aggregation
我正在使用 Oracle。
有一个 table 作为:
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
... ...
我做不到,但是在堆栈溢出时建议了这个查询,并且有效:
select sum(case when type = 1 then value else - value end) as value
from table t
group by year;
但是现在,我有另一种情况。我需要做同样的事情但不是 1-2-3-4-5-... 但是 1+2-3-4-5-6....
为此,我尝试了这两个查询,但都没有成功:
select sum(case when type = 1 then value when type = 2 then value else - value end) as value
from table t
group by year;
这导致第二个值的值翻了一番。
select sum(case when type = 1 then value else - value end)+case when type = 2 then value as value
from table t
group by year;
这导致了正确的类型 2 值,但是,由于此类型 2 仅在某些年份出现,其他年份显示为空。因此,最终计算对于类型 2(它所在的年份)是正确的,但对于每隔一年,对于每个类型 2 不存在,它 returns null.
我只是没能使这个查询正常工作..
任何想法将不胜感激!
谢谢
确定数字是应该被视为正数还是负数需要在您的聚合内部发生 SUM()
。所以:
select sum(case when type = 1 OR type = 2 then value else - value end)
from table t
group by year;
因为在您的 1+2-3-4-5-6... 公式中 1 和 2 都是正数(暗示 1 是正数),所以您需要 OR 来确保两者都是正数并且其他一切都是消极的。然后它会被总结和你的黄金。
使用 sign
的简短版本:
select year, sum(sign(-type+2.5)*value) from table t group by year
为了完整起见,两个替代解决方案:
select sum(case when type in (1, 2) then value else -value end)
from t
group by year;
或者,使用简单的 case 表达式:
select sum(case type
when 1 then value
when 2 then value
else -value
end)
from t
group by year;
我正在使用 Oracle。
有一个 table 作为:
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
... ...
我做不到,但是在堆栈溢出时建议了这个查询,并且有效:
select sum(case when type = 1 then value else - value end) as value
from table t
group by year;
但是现在,我有另一种情况。我需要做同样的事情但不是 1-2-3-4-5-... 但是 1+2-3-4-5-6....
为此,我尝试了这两个查询,但都没有成功:
select sum(case when type = 1 then value when type = 2 then value else - value end) as value
from table t
group by year;
这导致第二个值的值翻了一番。
select sum(case when type = 1 then value else - value end)+case when type = 2 then value as value
from table t
group by year;
这导致了正确的类型 2 值,但是,由于此类型 2 仅在某些年份出现,其他年份显示为空。因此,最终计算对于类型 2(它所在的年份)是正确的,但对于每隔一年,对于每个类型 2 不存在,它 returns null.
我只是没能使这个查询正常工作.. 任何想法将不胜感激! 谢谢
确定数字是应该被视为正数还是负数需要在您的聚合内部发生 SUM()
。所以:
select sum(case when type = 1 OR type = 2 then value else - value end)
from table t
group by year;
因为在您的 1+2-3-4-5-6... 公式中 1 和 2 都是正数(暗示 1 是正数),所以您需要 OR 来确保两者都是正数并且其他一切都是消极的。然后它会被总结和你的黄金。
使用 sign
的简短版本:
select year, sum(sign(-type+2.5)*value) from table t group by year
为了完整起见,两个替代解决方案:
select sum(case when type in (1, 2) then value else -value end)
from t
group by year;
或者,使用简单的 case 表达式:
select sum(case type
when 1 then value
when 2 then value
else -value
end)
from t
group by year;