我需要在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
我想只运行一个选择来获得A,B,C ....
答案 0 :(得分:1)
我想你可以试试这个:
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;
输出:
one two three four a b c
1 1 2 3 4 10 20 30
2 5 6 7 8 NULL 100 NULL
答案 1 :(得分:0)
尝试这样:
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