0

I need to improve this query in PostgreSQL

select a.*
            ,(select num
                    from TABLEA c
                 where c.one = a.one
                     and c.two = a.two
                     and c.three = a.three
                     and c.four= a.four
                     and  c.five = 'A') as A
            ,(select num
                    from TABLEA c
                 where c.one = a.one
                     and c.two = a.two
                     and c.three = a.three
                     and c.four = a.four
                     and c.five = 'B') as B
            ,(select num
                    from TABLEA c
                 where c.one = a.one
                     and c.two = a.two
                     and c.three = a.three
                     and c.four = a.four
                     and c.five = 'C') as C
                from TABLEB a

I'd like to run only one select to get A, B, C....

0

2 Answers 2

1

I think you can try this:

SELECT A.*, 
        C.A, C.B, C.C
FROM TABLEB A
LEFT JOIN (
    SELECT one, two, three, four
        , MAX( CASE WHEN five = 'A' THEN num ELSE NULL END) AS A
        , MAX( CASE WHEN five = 'B' THEN num ELSE NULL END) AS B
        , MAX( CASE WHEN five = 'C' THEN num ELSE NULL END) AS C
    FROM TABLEA 
    WHERE five IN ('A','B','C')
    GROUP BY one, two, three, four
) C ON  c.one = a.one
                     and c.two = a.two
                     and c.three = a.three
                     and c.four= a.four;

Output:

    one two three   four    a       b   c
1   1   2   3       4       10      20  30
2   5   6   7       8       NULL    100 NULL
Sign up to request clarification or add additional context in comments.

1 Comment

Your query is incredible! Thanks very much!!
0

try like this:

select 
(CASE WHEN five = 'A' THEN num ELSE NULL END),
(CASE WHEN five = 'B' THEN num ELSE NULL END),
(CASE WHEN five = 'C' THEN num ELSE NULL END)
from TABLEA 

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.