我在SQL中有2个表
|Name|Pos|Section| |ID |Month|Pos|Section|
------------------ -----------------
|Jim |Sup| HD | |R01|Jan |Sup| SA |
|Don |Sup| SA | |R02|Jan |Ast| SA |
|Rin |Ast| SA | |R03|Feb |Ast| HD |
|Boy |Ast| HD | |R04|Jan |Sup| HD |
我需要用于数据的命令字符串,如下表。
|ID |Month|Pos|Section|Name|
----------------------------
|R01|Jan |Sup| SA |Don |
|R02|Jan |Ast| SA |Rin |
|R04|Jan |Sup| HD |Jim |
请帮助我。
答案 0 :(得分:1)
简单的JOIN
将返回匹配的输入结果:
SELECT TT.ID, TT.[Month], TT.Pos, TT.Section, TO.[Name]
FROM TableTwo TT
JOIN TableOne TO ON TO.Pos = TT.Pos AND TO.Section = TT.Section
WHERE TT.[Month] = 'Jan'
答案 1 :(得分:1)
declare @tab1 table (Name varchar(50),Pos varchar(50),Section varchar(50))
declare @tab2 table (ID varchar(50),Month2 varchar(50),Pos varchar(50),Section varchar(50))
insert into @tab1
select 'Jim','Sup','HD'
union
select 'Don ','Sup','SA'
union
select 'Rin ','Ast','SA'
union
select 'Boy ','Ast','HD'
insert into @tab2
select 'R01','Jan','Sup','SA'
union
select 'R02','Jan','Ast','SA'
union
select 'R03','Feb','Ast','HD'
union
select 'R04','Jan','Sup','HD'
--select * from @tab1
--select * from @tab2
select t2.*,t1.Name
from @tab1 t1
inner join @tab2 t2 on t2.Section = t1.Section and t1.Pos = t2.Pos
and t2.Month2 = 'Jan'
输出:
ID Month2 Pos Section Name
R01 Jan Sup SA Don
R02 Jan Ast SA Rin
R04 Jan Sup HD Jim
答案 2 :(得分:1)
尝试通过以下查询联接两个表:
Select Table2.ID,Table2.Month,Table2.Pos,Table2.Section,Table1.Name
From Table2 INNER JOIN Table1
ON Table2.Section =Table1.Section
AND Table2.Pos=Table1.Pos
AND Table2.Month='Jan'