如何将正数和负数的sum()分成其他行

时间:2016-07-06 09:09:16

标签: sql oracle

表1

-------------
|  a  |  b  |
-------------
| -1 |  1  |
|  5 |  3  |
| -4 | -4  |
|  6 |  7  |
|  9 | -2  |
-------------

答案

negative :
positive :

修改

不使用union是一种特殊情况。

3 个答案:

答案 0 :(得分:2)

您可以使用CASE

中包含的SUM执行此操作

测试数据

CREATE TABLE #TestData (a int, b int)
INSERT INTO #TestData (a,b)
VALUES
 (-1,1)
,(5,3)
,(-4,-4)
,(6,7)
,(9,-2)

查询

SELECT 
 SUM((CASE WHEN A > 0 THEN A ELSE 0 END) + (CASE WHEN B > 0 THEN B ELSE 0 END)) Positive
,SUM((CASE WHEN A < 0 THEN A ELSE 0 END) + (CASE WHEN B < 0 THEN B ELSE 0 END)) Negative
FROM #TestData

输出

Positive    Negative
31          -11

如果你需要两行,试试这个

SELECT 
 'Positive' DataType
,SUM((CASE WHEN A > 0 THEN A ELSE 0 END)) A
,SUM((CASE WHEN B > 0 THEN B ELSE 0 END)) B
FROM #TestData
UNION ALL
SELECT 
 'Negative' DataType
,SUM((CASE WHEN A < 0 THEN A ELSE 0 END)) A
,SUM((CASE WHEN B < 0 THEN B ELSE 0 END)) B
FROM #TestData

结果

DataType    A   B
Positive    20  11
Negative    -5  -6

或者这个

SELECT 
 'Positive' DataType
,SUM((CASE WHEN A > 0 THEN A ELSE 0 END) + (CASE WHEN B > 0 THEN B ELSE 0 END)) Result
FROM #TestData
UNION ALL
SELECT 
 'Negative' 
,SUM((CASE WHEN A < 0 THEN A ELSE 0 END) + (CASE WHEN B < 0 THEN B ELSE 0 END)) 
FROM #TestData

结果

DataType    Result
Positive    31
Negative    -11

好的,没有UNION你可以像这样使用

SELECT 
DataType
,result
FROM 
(
    SELECT 
     SUM((CASE WHEN A > 0 THEN A ELSE 0 END) + (CASE WHEN B > 0 THEN B ELSE 0 END)) Positive
    ,SUM((CASE WHEN A < 0 THEN A ELSE 0 END) + (CASE WHEN B < 0 THEN B ELSE 0 END)) Negative
    FROM #TestData
) pr
UNPIVOT
(
    result
    for DataType in (Positive, Negative)
)u

结果

DataType    result
Positive    31
Negative    -11

答案 1 :(得分:1)

with cte as 
(
    select a as ab from tablename
    union all
    select b from tablename
)
select 'positive', sum(ab) from cte where ab > 0
union all
select 'negative', sum(ab) from cte where ab < 0

答案 2 :(得分:1)

您可以使用SIGN功能进行分组:

  SELECT CASE WHEN SUM(x) >= 0 THEN 'positive:' ELSE 'negative' END as sign, SUM (x) as result
    FROM (SELECT *
            FROM TABLE_NAME UNPIVOT (x FOR y IN (a AS 'a', b AS 'b')))
 WHERE x <> 0
GROUP BY SIGN (x)

没有PIVOT;)

  SELECT CASE rn WHEN 1 THEN 'positive:' ELSE 'negative' END SIGN, 
         SUM (CASE SIGN (a)WHEN rn THEN a ELSE 0 END + 
              CASE SIGN (b) WHEN rn THEN b ELSE 0 END) result
    FROM TABLE_NAME x
         JOIN (    SELECT ROWNUM - 2 rn
                     FROM DUAL
               CONNECT BY LEVEL < 4) y
            ON rn <> 0
GROUP BY rn