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

How to resolve subquery return more than one value in oracle

Could somebody please help me how to achieve the following?

Table:

ID      NAME       ROLE
1       KONDA      LEAD
1       SATHI      CO-LEAD
1       JOHN       CO-LEAD
2       REDDY      LEAD
2       SURESH     CO-LEAD
3       PRASAD     LEAD

My output should look like

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

ID      LEAD       CO-LEAD_1       CO-LEAD_2
1       KONDA      SATHI           JOHN
2       REDDY      SURESH
3       PRASAD

Thanks Inadvance.

>Solution :

We can use conditional aggregation with the help of ROW_NUMBER():

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ID, ROLE ORDER BY NAME) rn
    FROM yourTable t
)

SELECT
    ID,
    MAX(CASE WHEN ROLE = 'LEAD' THEN NAME END) AS LEAD,
    MAX(CASE WHEN ROLE = 'CO-LEAD' AND rn = 1 THEN NAME END) AS "CO-LEAD_1",
    MAX(CASE WHEN ROLE = 'CO-LEAD' AND rn = 2 THEN NAME END) AS "CO-LEAD_2",
FROM cte
GROUP BY ID
ORDER BY ID;
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