0

I want to sum of values of one column group by another column. e.g

Month     Count
Jan         5
Jan         7
Feb         1
Feb         2

I want

Month     Count   Status
Jan         5       A
Jan         7       B
Jan        12      SUM
Feb         1       A
Feb         2       B
Feb         3      SUM
1
  • 2
    Where do the status 'A' and 'B' come from? These doesn't exist in the original table. If you had a third record in January, what should be its status? 'C'? And what about the status of the 10000th record? Commented Aug 28, 2013 at 11:47

4 Answers 4

3

One way to do this is with rollup. However, because you want the original data, this approach does a "fake" aggregation by rownum for the rollup:

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)

I'm not sure what you mean by the A and B in the status column.

Sign up to request clarification or add additional context in comments.

Comments

1

The original table:

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');

The query:

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

Result:

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

Here is the SQLfiddle.

Comments

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

It will give net total as well, if you want to avoid it use month is not null.

2 Comments

This assumes the counts are different within a month.
Yes, you are right. I should number it and rollup based on it as you did. Thanks for pointing it out.
0

Oracle have MODEL clause for the above: If you've the column status in your table, you have simple query:

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.