Postgresql SELECT LEFT JOIN with case on case

时间:2018-02-14 09:42:45

标签: sql postgresql left-join

SELECT a1,a2,a3,a4,count(a5),b1,b2,b3
FROM table1
LEFT JOIN table2 ON a1=b1 AND a2=b2 (*here i need to join
              next columns a3=b3 only if from table2 will be returned more than 1 records 
    other wise first 2 columns will be enough*)
group by a1,a2,a3,a4,a5,b1,b2,b3

有人知道如何执行这个技巧吗?

1 个答案:

答案 0 :(得分:1)

好吧,如果我理解正确的话:

FROM table1 t1 LEFT JOIN
     (SELECT t2.*, COUNT(*) OVER (PARTITION BY b1, b2) as cnt
      FROM table2 t2
     )
     ON t1.a1 = t2.b1 AND t1.a2 = t2.b2 AND
        (cnt = 1 OR t1.a3 = t2.a3)