如果您使用 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
这是输出:
John Y Y Y
Mary Y Y