我可以使用Pivot吗?

时间:2016-05-09 07:02:17

标签: sql sql-server

我有一张包含以下数据的表格。

ID   | NAME | DPT | Country | School  | Course
-------------------------------------------------------------------
8888 | John | ABC | Japan   | ABC Uni | English
8888 | John | ABC | Japan   | ABC Uni | Engineering
8888 | John | ABC | England | EFG Uni | IS
8888 | John | XYZ | Japan   | ABC Uni | English
8888 | John | XYZ | Japan   | ABC Uni | Engineering
8888 | John | XYZ | England | EFG Uni | IS

我想把桌子变成这样。

ID   | NAME | DPT | Country1 | School1 | Course1 | Country2 | School2 | Course2     | Country3 | School3 | Course3
--------------------------------------------------------------------------------------------------------------------
8888 | John | ABC | Japan    | ABC Uni | English | Japan    | ABC Uni | Engineering | England  | EFG Uni | IS
8888 | John | XYZ | England  | ABC Uni | English | Japan    | ABC Uni | Engineering | England  | EFG Uni | IS

应按DPT排序,国家,学校和课程应分为Country1,Country2等,如上图所示。我怎样才能实现这一目标?请善意的建议。感谢。

CREATE TABLE #temp(
    [Id] [varchar](200) NULL,
    [Name] [varchar](200) NULL,
    [Department] [varchar](200) NULL,
    [UD_Country] [varchar](50) NULL,
    [UD_School] [varchar](50) NULL,
    [UD_Course] [varchar](50) NULL
) ON [PRIMARY]


INSERT INTO #temp VALUES 
('8888','John', 'ABC','Japan', 'ABC University', 'English'),
('8888','John', 'ABC','Japan', 'ABC University', 'Engineering'),
('8888','John', 'ABC','England', 'EFG University', 'IS'),
('8888','John', 'XYZ','Japan', 'ABC University', 'English'),
('8888','John', 'XYZ','Japan', 'ABC University', 'Engineering'),
('8888','John', 'XYZ','England', 'EFG University', 'IS')

1 个答案:

答案 0 :(得分:2)

WITH TempWithCountrySeqeunce AS (
    SELECT Id
         , Name
         , Department
         , UD_Country
         , ROW_NUMBER() OVER (PARTITION BY Id, Name, Department ORDER BY Id) AS CountrySequence 
         , UD_School
         , UD_Course
    FROM #temp
)
SELECT Id
      ,Name
      ,Department
      ,MAX(CASE WHEN CountrySequence = 1 THEN UD_Country END) AS Country1
      ,MAX(CASE WHEN CountrySequence = 1 THEN UD_School END) AS School1
      ,MAX(CASE WHEN CountrySequence = 1 THEN UD_Course END) AS Course1
      ,MAX(CASE WHEN CountrySequence = 2 THEN UD_Country END) AS Country2
      ,MAX(CASE WHEN CountrySequence = 2 THEN UD_School END) AS School2
      ,MAX(CASE WHEN CountrySequence = 2 THEN UD_Course END) AS Course2
FROM TempWithCountrySeqeunce  
GROUP BY Id
        ,Name
        ,Department

根据需要添加更多列