oracle SQL 上的条件求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33234844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditional SUM on oracle SQL
提问by Imran Hemani
I have the data in the follow way:
我有以下方式的数据:
ITEM LOCATION UNIT RETAIL QUANTITY
100 KS 10 -10
200 KS 20 30
I want the sum of positive quantities (quantity > 0) and sum of negative quantities (quantity < 0).
我想要正数量的总和(数量 > 0)和负数量的总和(数量 < 0)。
How do I get those column sum based on condition?
如何根据条件获得这些列总和?
回答by Lukasz Szozda
回答by MT0
You can use GREATEST
and LEAST
in conjunction with the SUM
function:
您可以使用GREATEST
和LEAST
与该SUM
功能结合使用:
Oracle 11g R2 Schema Setup:
Oracle 11g R2 架构设置:
CREATE TABLE table_name ( ITEM, LOCATION, QUANTITY ) AS
SELECT 100, 'KS', -10 FROM DUAL
UNION ALL SELECT 100, 'KS', -10 FROM DUAL
UNION ALL SELECT 100, 'KS', -20 FROM DUAL
UNION ALL SELECT 100, 'KS', 10 FROM DUAL
UNION ALL SELECT 100, 'KS', 5 FROM DUAL
UNION ALL SELECT 200, 'KS', 10 FROM DUAL
UNION ALL SELECT 200, 'KS', 20 FROM DUAL
UNION ALL SELECT 200, 'KS', 5 FROM DUAL
Query 1:
查询 1:
SELECT item,
location,
SUM( GREATEST( quantity, 0 ) ) AS positive_quantities,
SUM( LEAST( quantity, 0 ) ) AS negative_quantities
FROM table_name
GROUP BY item, location
结果:
| ITEM | LOCATION | POSITIVE_QUANTITIES | NEGATIVE_QUANTITIES |
|------|----------|---------------------|---------------------|
| 100 | KS | 15 | -40 |
| 200 | KS | 35 | 0 |