单行中的多个列值

时间:2013-01-31 05:37:42

标签: sql sql-server sql-server-2008

我有这样的表

    ID    Status
     1    5
     1    6
     1    7
     2    5
     2    6
     2    7

我需要如下结果

     ID      col1    col2    col3
     1        5       6       7
     2        5       6       7

请帮帮我

2 个答案:

答案 0 :(得分:4)

SELECT  ID,
        MAX(CASE WHEN status = 5 THEN Status ELSE NULL END) col1,
        MAX(CASE WHEN status = 6 THEN Status ELSE NULL END) col2,
        MAX(CASE WHEN status = 7 THEN Status ELSE NULL END) col3
FROM    tableNAME
GROUP   BY ID

使用PIVOT

SELECT *
FROM   (
          SELECT ID, Status, CASE Status 
                              WHEN 5 THEN 'Col1'
                              WHEN 6 THEN 'Col2'
                              WHEN 7 THEN 'Col3'
                            END Stat
          FROM tableName
        ) src
        PIVOT
        (
          MAX(Status)
          FOR Stat IN ([Col1],[Col2],[Col3])
        ) pivotTbl

答案 1 :(得分:0)

尝试未知计数目标列

--Create table TESTx (id int,status int)
--insert into TESTx Values (1,5),(1,6),(1,7),(1,17),(2,5),(2,7),(2,8),(3,1),(3,5);

-

Declare @Tab Varchar(50)='##tmp' +  Replace(Cast(newID() as Varchar(36)),'-','')

Declare @SQL Varchar(max)

Declare @Cols Varchar(max)
Declare @Renames Varchar(max)



Select @Cols ='Create Table ' + @Tab + '(ID int'
Select  @Cols=@Cols + ',[Col'+ Cast(Status as varchar(10))+'] int'
from 
(Select  Distinct top 1000 Status
from 
TESTx order by Status
) a

Select  @Cols=@Cols +')'

Select @SQL= @Cols
+' Insert into '+@Tab +' (ID) Select Distinct ID from TESTx'

exec(@SQL)

Declare @Status int

DECLARE P_cursor CURSOR FOR 
SELECT Distinct Status from TESTx 

OPEN P_cursor

FETCH NEXT FROM P_cursor 
INTO @Status

WHILE @@FETCH_STATUS = 0
BEGIN
   Select @SQL='Update ' + @Tab + ' Set Col' + CAST(@Status as Varchar(10)) +'=' +Cast(@Status as Varchar(10))
               +' from TESTx Where TESTx.ID=' + @Tab  +'.ID and Testx.Status=' +Cast(@Status as Varchar(10))
   Exec(@SQL)            
   FETCH NEXT FROM P_cursor 
   INTO @Status
END

CLOSE P_cursor
DEALLOCATE P_cursor

Select @SQL=' Select * from '+@Tab +'  Drop Table ' + @Tab 
Exec(@SQL)