0

如果源表是:

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 月的许多列。

4

1 回答 1

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
于 2012-06-17T21:08:00.853 回答