0

我想将一个列组的值与另一列相加。例如

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

4 回答 4

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)

我不确定状态栏中的Aand是什么意思。B

于 2013-08-28T11:47:04.320 回答
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

是 SQLfiddle。

于 2013-08-28T11:48:16.700 回答
0
select month, sum(count) from table group by rollup(month, count);

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

于 2013-08-28T11:46:51.807 回答
0

上面的Oracle 有MODEL子句:如果你的表中有列状态,你有简单的查询:

模型子句链接 Oracle 文档:

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 
于 2013-09-24T07:58:52.010 回答