2010-11-08 134 views
1

讓我盡我所能地描述這個,這是關於SQL Server的。SQL查詢需要返回主記錄和輔助記錄

有一個主表,每個參與者有一個記錄,每個參與者有一個最多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 

基本上行列的想法。

我該如何做到這一點?我總共虧損

回答

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' 
+0

這可以工作,但我只是檢查了桌子,最多可以有7個技能組記錄,但是有一個規定,技能組1-4是靜態的,具有不同的ID,但是技能組5-7是可選的並且具有相同的ID。 – mattgcon 2010-11-08 20:53:12

+0

@mattgcon:如果他們有相同的ID,你會如何區分5-7? – 2010-11-08 21:06:22

+0

由輸入技能類型文本的可選列組成 – mattgcon 2010-11-08 21:20:23

-1
SELECT * 
FROM Main_Table, Sub_Table 
WHERE Main_Table.Participant_ID = Sub_Table.Participant_ID; 

SQL Server是否使用標準SQL?

+0

這是行不通的。主表不包含子表內的任何信息,除了參與者ID – mattgcon 2010-11-08 19:21:56

+0

另外你在這裏做一個交叉連接.... – JNK 2010-11-08 19:26:35

+0

@mattgcon:你是什麼意思?您需要的唯一相交數據是Participant_ID的值,而'SELECT *'將返回兩個表中的所有列。請注意,它會返回笛卡爾積,所以我會建議使用'SELECT DISTINCT *'來過濾掉冗餘的元組。 – 2010-11-08 19:27:46

0

你需要在這裏做一個關鍵。但是你的情況的問題是你需要在多個列上進行轉換。我希望您能指出正確的方向Multiple Column Pivot in T-SQL

+0

LOL我試過這個支點,但是我看起來更困惑,然後一隻猴子試圖讀一本書。 – mattgcon 2010-11-08 20:34:38