oracle SQL上的条件SUM

时间:2015-10-20 10:59:12

标签: sql oracle sum conditional-statements

我的数据如下:

ITEM  LOCATION  UNIT RETAIL  QUANTITY 
100     KS         10          -10
200     KS         20           30

我想要正数量的总和(数量> 0)和负数量的总和(数量<0)。

如何根据条件获得这些列总和?

2 个答案:

答案 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)

您可以将GREATESTLEASTSUM功能结合使用:

SQL Fiddle

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 |