Sql-Server

在一個結果中加入一對多欄位而不連接

  • September 5, 2019

我遇到了與在單個結果中連接一對多欄位相同的問題嗎?,但我需要一個結果,其中“許多”欄位佔據它們自己的列並且沒有連接在一列中。有什麼建議麼?

樣本數據:

___ID      Mapped_Heading    Source_Value
1          English           pass
1          Math              pass
1          History           fail


___ID      Name              Age
1          Bob               12
2          Harry             12
3          Emily             14

最終結果將是:

___ID      Name      Age  English   Math   History
1          Bob       12   pass      pass   fail

我希望我不必使用PIVOTPARTITION BY因為我不熟悉這些功能,但我一直在為這個問題碰到它們,所以我想我可能不得不這樣做嗎?

一種方法是使用PIVOT.

這是設置程式碼:

create table grades (
 ID             int,
 Mapped_Heading varchar(10),
 Source_Value   varchar(10)
);
create table students (
 ID   int,
 Name varchar(10),
 Age  int
);
insert grades 
values
(1,'English', 'pass'),
(1,'Math',    'pass'),
(1,'History', 'fail');
insert students
values
(1, 'Bob',   12),
(2, 'Harry', 12),
(3, 'Emily', 14);

這是PIVOT程式碼:

with temp as (
 select s.*, g.Mapped_Heading, g.Source_Value
 from students s
 join grades g on g.ID = s.ID
)
select * 
from (
   select * 
   from temp
) a
pivot (
   max(Source_Value)
   for Mapped_Heading in ([English],[Math],[History])
) as b

輸出如下所示:

+----+------+-----+---------+------+---------+
| ID | Name | Age | English | Math | History |
+----+------+-----+---------+------+---------+
| 1  | Bob  | 12  | pass    | pass | fail    |
+----+------+-----+---------+------+---------+

db<>小提琴展示

引用自:https://dba.stackexchange.com/questions/246970