将列的名称显示为数据

时间:2012-06-17 20:31:21

标签: sql sql-server-2008

如果源表是:

City         1996-MAY  1996-june  1996-july 1996-aug  1996-sep  1996-okt
 -----------  --------  --------  --------  --------  --------  --------
New Orleans         6          3         3         3         3         3    
Los Angeles         4          3         3         3         3         3
select city, 1996-MAY, 1996-june, 1996-july, 1996-aug, 1996-sep, 1996-okt
  from a  

请求的结果是:

City         People    Date
-----------  --------  --------
New Orleans         6  1996-MAY
Los Angeles         4  1996-MAY  
New Orleans         3  1996-june
Los Angeles         3  1996-june  
New Orleans         3  1996-july 
Los Angeles         3  1996-july 
....            ...        .....  

我该怎么做?

这不仅仅是一列,而是截至2003年5月的很多专栏。

1 个答案:

答案 0 :(得分:3)

使用UNPIVOT

SELECT  City, Date, People
FROM    T
        UNPIVOT 
        (   People 
            FOR Date IN ([1996-May], [1996-June], [1996-July])
        ) upvt

您也可以动态执行此操作:

DECLARE @SQL NVARCHAR(MAX) = ''

SELECT  @SQL = ',' + QUOTENAME(Name)
FROM    SYS.COLUMNS 
WHERE   OBJECT_ID = OBJECT_ID('TableName')  
AND     Name != 'City'

SET @SQL = 'SELECT  City, Date, People
            FROM    T
                    UNPIVOT 
                    (   People 
                        FOR Date IN (' + STUFF(@SQL, 1, 1, '') + ')
                    ) upvt'

EXECUTE SP_EXECUTESQL @SQL