根据oracle中的列获取行的总和

时间:2013-08-28 11:33:22

标签: oracle

我希望将一个列组的值与另一列的值相加。 e.g

Month     Count
Jan         5
Jan         7
Feb         1
Feb         2

我想要

Month     Count   Status
Jan         5       A
Jan         7       B
Jan        12      SUM
Feb         1       A
Feb         2       B
Feb         3      SUM

4 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是使用rollup。但是,因为您需要原始数据,所以此方法通过rownum进行“假”聚合以进行汇总:

select Month, sum(Count),
       (case when rn is null then 'SUM' end) as status
from (select rownum as rn, t.*
      from t
     ) t
group by Month, rollup(rn)

我不确定状态列中AB的含义。

答案 1 :(得分:1)

原始表:

CREATE TABLE test
(
    month CHAR(3), 
    num INT,
    status CHAR(3)
);

INSERT INTO test (month, num, status) VALUES
    ('Jan', 5, 'A'),
    ('Jan', 7, 'B'),
    ('Feb', 1, 'A'),
    ('Feb', 2, 'B');

查询:

SELECT month, sum(num) AS num, 'SUM' AS status
FROM test
GROUP BY month
UNION
SELECT month, num, status
FROM test
ORDER BY month DESC, status

结果:

MONTH   NUM   STATUS
Jan     5     A
Jan     7     B
Jan     12    SUM
Feb     1     A
Feb     2     B
Feb     3     SUM

Here是SQLfiddle。

答案 2 :(得分:0)

select month, sum(count) from table group by rollup(month, count);

它也会给出净总数,如果你想避免使用月份则不为空。

答案 3 :(得分:0)

Oracle上面有MODEL子句: 如果您在表格中有列状态,则可以进行简单的查询:

Model Clause Link Oracle Documentation:

SELECT month, count , status
FROM my_test2
MODEL
PARTITION BY (MONTH)
DIMENSION BY (status)
MEASURES(count)
RULES(COUNT['Sum'] = count['A']+ count['B'])
order by month desc, status;


MONTH                     COUNT STATUS             
-------------------- ---------- --------------------
Jan                           5 A                    
Jan                           7 B                    
Jan                          12 Sum                  
Feb                           1 A                    
Feb                           2 B                    
Feb                           3 Sum                  

 6 rows selected