如何将行转换为列?

时间:2016-11-08 15:22:19

标签: tsql pivot transpose

可能是一个简单的方法,有没有办法快速转置我的数据,使其读取而不是按行读取。

enter image description here

以上是当前的输出,但希望能够阅读,例如

AttendanceNumber, ExamDate, ExamCode1, ExamCode2, ExamCode3, .......ExamCode20

我的sql是

SELECT  [AttendanceNumber]
       ,[ExaminationDate]
       ,[ExamExaminationCode]
  FROM [Radiotherapy].[dbo].[tblRadiologyData] rd 
  where rd.ExaminationDate >= '01 april 2016'
  and   rd.AttendanceSiteCode IN('CNM','RNM')
  ORDER BY rd.LocalPatientIdentifier, rd.ExaminationDate

1 个答案:

答案 0 :(得分:1)

您可以对ROW_NUMBER()使用条件聚合:

SELECT s.attendanceNumber,s.examinationDate,
       MAX(CASE WHEN s.rnk = 1 THEN s.ExamExaminationCode END) as examCode1,
       MAX(CASE WHEN s.rnk = 2 THEN s.ExamExaminationCode END) as examCode2,
       MAX(CASE WHEN s.rnk = 3 THEN s.ExamExaminationCode END) as examCode3,
       ..... As many as you need
FROM (
    SELECT  [AttendanceNumber]
           ,[ExaminationDate]
           ,[ExamExaminationCode]
           ,ROW_NUMBER() OVER(PARTITION BY [AttendanceNumber] ORDER BY [ExaminationDate]) as rnk --Ordered by date ASC 
      FROM [Radiotherapy].[dbo].[tblRadiologyData] rd 
      where rd.ExaminationDate >= '01 april 2016'
      and   rd.AttendanceSiteCode IN('CNM','RNM') ) s
GROUP BY s.attendanceNumber,s.examinationDate