我有两个mssql表,其数据如下:
table_fruit
id valueid valuetext
111 1 apple
111 2 pear
111 3 orange
112 1 kiwi
112 2 pear
112 3 banana
table_people
id name
111 bob
112 george
我希望使用上面两个表在这样的单行上得到最终结果:
name fruit1 fruit2 fruit3
bob apple pear orange
george kiwi pear banana
我已尝试加入在id上链接的表格,但最终在结果网格中每个ID有三行?
感谢您寻找
答案 0 :(得分:2)
解决方案1(未测试)
SELECT name, [0] fruit1, [1] fruit2, [2] fruit3
FROM
(
SELECT f0.id, f0.name, f1.valuetext, f1.valueid
from table_people f0 left outer join table_fruit f1 on f0.id=f1.id
) AS SourceTable
PIVOT
(
MAX(valuetext) FOR valueid IN ([0], [1], [2])
) AS PivotTable;
答案 1 :(得分:0)
解决方案3:
select f0.name,
f1.valuetext fruit1, f2.valuetext fruit2, f3.valuetext fruit3
from table_people f0
left outer join table_fruit f1 on f0.id=f1.id and f1.valueid=1
left outer join table_fruit f2 on f0.id=f2.id and f2.valueid=2
left outer join table_fruit f3 on f0.id=f3.id and f3.valueid=3
答案 2 :(得分:0)
解决方案2:
select f0.name,
Max(case when f1.valueid=1 then f1.valuetext else cast(null as varchar(1)) end) fruit1,
Max(case when f1.valueid=2 then f1.valuetext else cast(null as varchar(1)) end) fruit2,
Max(case when f1.valueid=3 then f1.valuetext else cast(null as varchar(1)) end) fruit3
from table_people f0
left outer join table_fruit f1 on f0.id=f1.id
group by f0.id, f0.name
答案 3 :(得分:0)
是的,MSSQL也支持PIVOT子句。您可以参考这篇文章:https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx