我的数据如下:
ITEM LOCATION UNIT RETAIL QUANTITY
100 KS 10 -10
200 KS 20 30
我想要正数量的总和(数量> 0)和负数量的总和(数量<0)。
如何根据条件获得这些列总和?
答案 0 :(得分:14)
您可以使用SUM(CASE ... )
:
SELECT item, location,
SUM(CASE WHEN quantity > 0 THEN quantity ELSE 0 END) AS positive_sum,
SUM(CASE WHEN quantity < 0 THEN quantity ELSE 0 END) AS negative_sum
FROM your_table
GROUP BY item, location;
的 LiveDemo
强>
答案 1 :(得分:1)
您可以将GREATEST
和LEAST
与SUM
功能结合使用:
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
查询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
<强> Results 强>:
| ITEM | LOCATION | POSITIVE_QUANTITIES | NEGATIVE_QUANTITIES |
|------|----------|---------------------|---------------------|
| 100 | KS | 15 | -40 |
| 200 | KS | 35 | 0 |