首页 > 解决方案 > SQL如何将B表中的2列与表A中的一列进行比较,并且两者都必须在其中

问题描述

我想从表 a 和 b 中获取以下信息:

**Table A**           
user_id Function    
1       VES  
1       API         
1       LA          
1       POR         
5       MM          
5       POA         
5       VES 

 **Table B**    
Function     Functionrel  
VES          APP  
VES          API  
VES          MM  
VES          POA  
LA           MM  
MM           VES  
POA          LA  

我期望的输出是该特定用户的表 A 中的所有函数,并且在两列中都链接到表 B。我认为输出将如下所示。

USER_ID function    b.function  functionrel
1        VES         VES        API  
1        API         VES        API  
5        MM          MM         VES  
5        POA         VES        POA  
5        VES         VES        POA  
5        VES         MM         VES  

输出

我使用了以下语句,但这不正确,因为它没有使用 a.function 检查 b.functionalrel 列

select * from
(
SELECT *, 
 ROW_NUMBER() OVER 
 ( 
     PARTITION BY CONVERT(VARCHAR(100),a.user_id) + ' ' + a.function
     ORDER BY a.function DESC) as rn1
FROM A a 
)a
full outer join
(
select b.function, b.functionrel, row_number() over(PARTITION BY  b.function order by b.function) as rn2
from B b 
)b on a.function =  b.function
    and rn1=rn2;

希望有人可以帮助我

问候

标签: sql-scripts

解决方案


推荐阅读