Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ORACLE SQL, I don't know how to use SUM() here

Table TRANSACTION:

TRANS_VALUE USER ID TRANS_TYPE_ID
10 1 2
5 2 1
15 1 1
20 2 2
10 1 2
5 1 2
15 3 1
20 3 1

I need to get to this:

USER SUM(TRANS_TYPE_1) SUM(TRANS_TYPE_2)
1 15 25
2 5 20
3 35 NULL

Can someone help me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this but sadness

SELECT
    user_id AS "USER 
    SUM(trans_value)
FROM 
    TRANSACTION
WHERE 
    trans_value = 1
GROUP BY
    user_id
ORDER BY 1;

I need to get to this

USER SUM(TRANS_TYPE_1) SUM(TRANS_TYPE_2)
1 15 25
2 5 20
3 35 NULL

>Solution :

Use conditional aggregation:

SELECT user_id,
       SUM(CASE trans_type_id WHEN 1 THEN trans_value END) AS sum_trans_type_1,
       SUM(CASE trans_type_id WHEN 2 THEN trans_value END) AS sum_trans_type_2
FROM   transaction
GROUP BY user_id

or PIVOT:

SELECT *
FROM   transaction
PIVOT (
  SUM(trans_value)
  FOR trans_type_id IN (
    1 AS sum_trans_type_1,
    2 AS sum_trans_type_2
  )
)

Which, for the sample data:

CREATE TABLE transaction (TRANS_VALUE, USER_ID, TRANS_TYPE_ID) AS
SELECT 10, 1, 2 FROM DUAL UNION ALL
SELECT  5, 2, 1 FROM DUAL UNION ALL
SELECT 15, 1, 1 FROM DUAL UNION ALL
SELECT 20, 2, 2 FROM DUAL UNION ALL
SELECT 10, 1, 2 FROM DUAL UNION ALL
SELECT  5, 1, 2 FROM DUAL UNION ALL
SELECT 15, 3, 1 FROM DUAL UNION ALL
SELECT 20, 3, 1 FROM DUAL;

Both output:

USER_ID SUM_TRANS_TYPE_1 SUM_TRANS_TYPE_2
1 15 25
2 5 20
3 35 null

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading