0

I want to concatenate multiple rows to a sigle row in oracle. Below is what I am trying to achieve

case table

case_id Name
1       AAA
2       BBB

Subject table

case_id Subject
1       ENG
1       MATH
1       SCI
2       ENG
2       HIS

SUB_LOOKUP table

Abbr    Subject
ENG     English
MATH    Mathematics
SCI     Science
HIS     History

Expected Output

1   AAA     English, Mathematics, Science
2   BBB     English, History

I tried using LISTAGG function as below. It lists what I would want to achieve but the issue comes when I join with the lookup table and then join to main table.

SELECT c.case_id, c.category_id, LISTAGG(cs.special_interest_cd) WITHIN GROUP 
(ORDER BY cs.special_interest_cd) AS description
FROM CASE_SPECIAL_INTEREST cs, cases c
where c.case_id = cs.case_id
GROUP BY c.case_id;

Tried joining 2 tables but getting "ORA-00979: not a GROUP BY expression" Can someone help with joining the 3 tables. Is it possible to achieve the same without LISTAGG since i read it throws eception when the max character is reached for varchar?

1 Answer 1

2

You only need a basic join between the three tables, followed by an aggregation by case_id and name:

SELECT
    c.case_id,
    c.Name,
    LISTAGG(sl.subject, ',') WITHIN GROUP (ORDER BY sl.subject) AS subject
FROM "case" c
LEFT JOIN subject s
    ON c.case_id = s.case_id
LEFT JOIN sub_lookup sl
    ON s.Subject = sl.Abbr
GROUP BY
    c.case_id,
    c.Name;

screen capture of demo below

Demo

Note that I use left joins here, to ensure that if a given case_id has no matches for the aggregation, that record/value would still be reported in the result set.

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

2 Comments

thank you. When I run this query independently it works great and gives me result exactly like what i want. But I have to add this query inside an already exisiting query which is really huge and the result is 1 AAA Mathematics. I cant paste the original query here since its like 500 lines of code but any suggestions?
No, I can't make a suggestion without seeing the actual query.

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.