具有编号列名称的动态PIVOT

时间:2015-04-09 18:57:18

标签: sql dynamic pivot

尝试转动表时,我得到以下内容:

Country  Birmingham  Dallas  New Delhi
---------------------------------------
India    NULL        NULL    New Delhi
UK       Birmingham  NULL    NULL
USA      NULL        Dallas  NULL

但是,我试图得到这个(每个国家不同城市的总数):

Country City1        City2          City3
----------------------------------------
India  New Delhi     Bangalore      Hyderabad
UK     London        Birmingham     Portsmouth
USA    Dallas        Indianapolis   Houston

这是我目前正在使用的代码:

-- Dynamic Pivot
declare @dynamicPivQuery as nvarchar(max)
declare @colName as nvarchar(max)

--get distinct values of the pivot column
select @colName = 
    coalesce(@colName + ',','') + quotename(city)
    from (select distinct city from countries) as B
    order by b.city 



--Prepare the PIVOT query using the dynamic
SET @dynamicPivQuery =
    N'select Country, ' + @colName + '
    from countries
    pivot (MAX(City)
        for City in (' + @colName + ')) AS PIV'

EXEC sp_executesql @dynamicPivQuery 

Table Countries
  Country nvarchar(50)
  City    nvarchar(50)

我想知道我是否可以使用类似的东西:

'City' + CAST(Row_Number() over (partition by country order by country) as Varchar(10))

我正在使用SQL 2005服务器,数据库仍处于2000兼容模式。

谢谢

1 个答案:

答案 0 :(得分:1)

SELECT Country, [1] AS City1, [2] AS City2, [3] AS City3
FROM 
(
    SELECT 
        Country, 
        City,
        ROW_NUMBER() OVER(PARTITION BY Country ORDER BY Country) Seq
    FROM Countries
) s
PIVOT
(
    MAX(City)
    FOR Seq IN ([1], [2], [3])
) p

结果是:

Country City1       City2           City3
India   New Delhi   Bangalore       Hyderabad
UK      London      Birmingham      Portsmouth
USA     Dallas      Indianapolis    Houston