从多个表中选择,消除重复值

时间:2019-02-25 14:30:09

标签: sql postgresql

我有这些表和值:

Person                 Account                
------------------     -----------------------              
ID | CREATED_BY        ID | TYPE | DATA                 
------------------     -----------------------              
1 |                    1  | T1   | USEFUL DATA                
2 |                    2  | T2   |                 
3 |                    3  | T3   |
4 |                    4  | T2   |



Person_account_link                                       
--------------------------                     
ID | PERSON_ID | ACCOUNT_ID                                   
--------------------------                     
1 |  1         |   1                                
2 |  1         |   2                                  
3 |  2         |   3                        
4 |  3         |   4

我想选择所有具有T1帐户类型的人员,并获取数据列,对于其他人员,他们应该是没有任何帐户信息的结果。

(我注意到第1个人有两个帐户:account_id_1和account_id_2,但只能显示一行(如果存在T1类型的优先级,否则为空)

结果应为:

Table1             
----------------------------------------------------- 
PERSON_ID | ACCOUNT_ID | ACCOUNT_TYPE | ACCOUNT_DATA    
----------------------------------------------------- 
1         |  1         |    T1        |  USEFUL DATA       
2         |  NULL      |   NULL       |  NULL         
3         |  NULL      |   NULL       |  NULL         
4         |  NULL      |   NULL       |  NULL         

3 个答案:

答案 0 :(得分:2)

您可以进行条件聚合:

SELECT p.id,
       MAX(CASE WHEN a.type = 'T1' THEN a.id END) AS ACCOUNT_ID,
       MAX(CASE WHEN a.type = 'T1' THEN 'T1' END) AS ACCOUNT_TYPE,
       MAX(CASE WHEN a.type = 'T1' THEN a.data END) AS ACCOUNT_DATA 
FROM person p LEFT JOIN
     Person_account_link pl
     ON p.id = pl.person_id LEFT JOIN
     account a
     ON pl.account_id = a.id
GROUP BY p.id;

答案 1 :(得分:0)

您将需要一个外部联接,从Person开始,然后到其他两个表。我还将汇总group bymin来解决一个人拥有两个或多个T1帐户的情况。在这种情况下,将获取其中一个数据(其中的min):

select    p.id person_id,
          min(a.id) account_id,
          min(a.type) account_type,
          min(a.data) account_data
from      Person p
left join Person_account_link pa on p.id = pa.person_id
left join Account a on pa.account_id = a.id and a.type = 'T1'
group by  p.id

答案 2 :(得分:0)

在Postgres中,我喜欢使用FILTER关键字。另外,如果只希望有帐户的人,则不需要Person表。如果您想要所有人:

SELECT p.id,
       MAX(a.id) FILTER (a.type = 'T1') as account_id,
       MAX(a.type) FILTER (a.type = 'T1') as account_type,
       MAX(a.data) FILTER (a.type = 'T1') as account_data
FROM Person p LEFT JOIN
     Person_account_link pl
     ON pl.person_id = p.id LEFT JOIN
     account a
     ON pl.account_id = a.id
GROUP BY p.id;