在SQL Server中将行转换为列

时间:2018-03-29 02:16:08

标签: sql sql-server sql-server-2012

我有一个视图vw_Country,它返回以下记录:

enter image description here

我想使用此视图编写查询以返回以下结果:

enter image description here

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

如果没有要转动的列,则无法进行转动,但您可以创建要转动的列。这样的事情应该可行:

SELECT Rownum, [Australia], [India], [United States]
FROM 
    (SELECT ROW_NUMBER() OVER(PARTITION BY Country, ORDER BY City) AS Rownum, Country, City
        FROM vw_Country
        ) sourcetable
    PIVOT 
        (
        MIN(City)
        FOR Country IN ([Australia], [India], [United States])
        ) AS pvt
ORDER BY pvt.Rownum

答案 1 :(得分:0)

使用rank创建另一列,然后使用pivot。

Select [Australia], [India], [United States]
from 
(
  select Country, City, 
   Rank() over (partition by country order by city) as rnk
  from yourTable
) src
 pivot
(
 Max(City)
  for Country in ([Australia], [India], [United States])
) piv;