SQL连接表

Har*_*ley 6 sql foxpro visual-foxpro

表一包含

ID|Name  
1  Mary  
2  John  
Run Code Online (Sandbox Code Playgroud)

表二包含

ID|Color  
1  Red  
2  Blue  
2  Green  
2  Black  
Run Code Online (Sandbox Code Playgroud)

我想最终得到的是

ID|Name|Red|Blue|Green|Black  
1  Mary Y   Y  
2  John     Y     Y     Y
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.


谢谢你的回复.我将重新发布一些关于我正在尝试做的事情的其他信息,这可能会使这一点复杂化.有人可以关闭这个吗?

And*_*zub 6

如果您使用T-SQL,您可以使用PIVOT(http://msdn.microsoft.com/en-us/library/ms177410.aspx)

这是我使用的查询:

declare @tbl_names table(id int, name varchar(100))
declare @tbl_colors table(id int, color varchar(100))

insert into @tbl_names
select 1, 'Mary'
union
select 2, 'John'


insert into @tbl_colors
select 1, 'Red'
union
select 1, 'Blue'
union
select 2, 'Green'
union
select 2, 'Blue'
union
select 2, 'Black'

select name,
        case when [Red] is not null then 'Y' else '' end as Red,
        case when [Blue] is not null then 'Y' else '' end as Blue,
        case when [Green] is not null then 'Y' else '' end as Green,
        case when [Black] is not null then 'Y' else '' end as Black

from
(
select n.id, name, color from @tbl_names n
inner join @tbl_colors c on n.id = c.id
) as subq
pivot 
(
    min(id)
    FOR color IN ([Red], [Blue], [Green], [Black])
) as pvt
Run Code Online (Sandbox Code Playgroud)

这是输出:

John        Y   Y   Y
Mary    Y   Y       
Run Code Online (Sandbox Code Playgroud)