在SQL Server的更多列中为一个id显示多行

时间:2015-09-02 21:03:29

标签: sql sql-server-2008

我想在不同的列中显示行

现状

CASEID  DATE OF SERVICE
760      12/30/2008
760      12/30/2008
817      12/30/2008
817      12/30/2008
817      12/01/2009    

现在我想将其显示为

CASEID [DATE OF SERVICE1] [DATE OF SERVICE2] [Date of Service3] so-on
760      12/30/2008        12/30/2008
817       12/30/2008       12/30/2008        12/01/2009   

2 个答案:

答案 0 :(得分:1)

您可以使用CTE生成行号,然后自行连接奇数行和偶数行并从那里选择:

WITH rn AS (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY CASEID ORDER BY [DATE OF SERVICE]) rn
  FROM Cases
)
SELECT r1.CASEID, r1.[DATE OF SERVICE] as [DATE OF SERVICE1],
       r2.[DATE OF SERVICE] as [DATE OF SERVICE2]
FROM rn r1 LEFT JOIN rn r2
  ON r1.rn = r2.rn - 1 AND r1.CASEID = r2.CASEID
WHERE (r1.rn % 2) = 1

同样在SQLFiddle

答案 1 :(得分:0)

如果您知道任何CaseID的最大日期数,则可以使用Pivot。 (在这里,我假设任何CaseID我最多有5个日期)。

Select CaseID, [1] As [DOS1], [2] As [DOS2], [3] As [DOS3], [4] As [DOS4],   
[5] As [DOS5]
From
(Select CaseID, [Date Of Service], 
ROW_NUMBER() Over(Partition By CaseID Order by [Date Of Service]) RowNum
From Cases ) P
Pivot 
(
Max([Date Of Service]) For RowNum in ([1], [2], [3], [4], [5]) 
) As Pvt 
Order by CaseID