2017-09-15 3 views
0

Ich brauche diese Abfrage in PostgreSQL zu verbessernverbessern Abfrage in PostgresSQL

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 

Ich möchte nur ein wählen, um einen bekommen, B, C ....

Antwort

1

ich glaube, Sie dies versuchen:

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; 

Ausgabe:

one two three four a  b c 
1 1 2 3  4  10  20 30 
2 5 6 7  8  NULL 100 NULL 
+0

Ihre Anfrage ist unglaublich! Vielen Dank!! –

0

versuchen wie folgt aus:

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