让我尽可能地描述这一点,这是关于SQL Server的。
有一个主表,每个参与者有一条记录,每个参与者有一个子表,最多有5条记录。
我需要能够返回主表中的所有记录以及SELECT查询中同一记录中每个参与者的子表记录。
示例:
Main Table:
Participant_ID,
Program
Sub Table:
Participant_ID,
Skill_Set_ID,
Rating
SQL Query results:
Participant_ID, Program, Skill_Set_ID_1, Rating_1, Skill_Set_ID_2, Rating_2, Skill_Set_ID_3, Rating_3, Skill_Set_ID_4, Rating_4, Skill_Set_ID_5, Rating_5
基本上是行到列的想法。
我怎样才能完成这项工作?我完全失去了
答案 0 :(得分:1)
select mt.Participant_ID, mt.Program,
st1.Skill_Set_ID as Skill_Set_ID_1, st1.Rating as Rating_1,
st2.Skill_Set_ID as Skill_Set_ID_2, st2.Rating as Rating_2,
st3.Skill_Set_ID as Skill_Set_ID_3, st3.Rating as Rating_3,
st4.Skill_Set_ID as Skill_Set_ID_4, st4.Rating as Rating_4,
st5.Skill_Set_ID as Skill_Set_ID_5, st5.Rating as Rating_5, st5.Skill_Text
st6.Skill_Set_ID as Skill_Set_ID_6, st6.Rating as Rating_6, st6.Skill_Text
st7.Skill_Set_ID as Skill_Set_ID_7, st5.Rating as Rating_7, st7.Skill_Text
from main_table mt
left join sub_table st1
on mt.Participant_ID = st1.Paticipant_ID
and st1.Skill_Set_ID = 1
left join sub_table st2
on mt.Participant_ID = st2.Paticipant_ID
and st2.Skill_Set_ID = 2
left join sub_table st3
on mt.Participant_ID = st3.Paticipant_ID
and st3.Skill_Set_ID = 3
left join sub_table st4
on mt.Participant_ID = st4.Paticipant_ID
and st4.Skill_Set_ID = 4
left join sub_table st5
on mt.Participant_ID = st5.Paticipant_ID
and st5.Skill_Set_ID = 5
and st5.Skill_Text = 'Skill A'
left join sub_table st6
on mt.Participant_ID = st6.Paticipant_ID
and st6.Skill_Set_ID = 5
and st6.Skill_Text = 'Skill B'
left join sub_table st7
on mt.Participant_ID = st7.Paticipant_ID
and st7.Skill_Set_ID = 5
and st7.Skill_Text = 'Skill C'
答案 1 :(得分:0)
你需要在这里做一个转轴。但是你的案例的问题是你需要转向多个列。我希望这能指出你正确的方向Multiple Column Pivot in T-SQL
答案 2 :(得分:-1)
SELECT *
FROM Main_Table, Sub_Table
WHERE Main_Table.Participant_ID = Sub_Table.Participant_ID;
SQL Server是否使用标准SQL?