在SQL Server 2012中进行转置

时间:2016-11-03 15:20:15

标签: sql-server sql-server-2012

我有以下内容:




  Country | StateCity
 -------- + ------------
 USA | MO
美国| LA
美国| OH
加拿大|安大略省
加拿大|多伦多
  




我希望转换和统一标题,结果如




  USA CANADA
 MO Ontario
 LA Toronto
 OH
  



4 个答案:

答案 0 :(得分:1)

假设你不想去DYNAMIC

Declare @YourTable table (Country varchar(25),StateCity varchar(25))
Insert Into @YourTable values 
('USA','MO'),
('USA','LA'),
('USA','OH'),
('CANADA','Ontario'),
('CANADA','Toronto')

Select USA   =max(case when Country='USA'    then StateCity else '' end)
      ,CANADA=max(case when Country='CANADA' then StateCity else '' end)
 From ( Select *
              ,RowNr=Row_Number() over (Partition By Country Order By (Select NULL)) 
         From  @YourTable
       ) A
 Group By RowNr

返回

USA CANADA
MO  Ontario
LA  Toronto
OH  

答案 1 :(得分:1)

但如果你想要DYNAMIC: Sql DEMO

首先,您需要一个时态表来创建row_id

SELECT row_number() over (partition by [Country] order by [StateCity]) [rn], 
       [StateCity],
       [Country]
INTO temp
FROM State;

然后你可以去动态枢轴路线

创建不同的列

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Country]) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

创建透视查询:

set @query = 'SELECT rn, ' + @cols + ' from 
            (
                select [rn]
                     , [StateCity]
                     , [Country]
                from temp
           ) x
            pivot 
            (
                 max(StateCity)
                for [Country] in (' + @cols + ')
            ) p ';

执行

execute(@query);

<强>输出:

enter image description here

答案 2 :(得分:0)

这更像是客户端问题。您要查找的结果不是数据库查询生成的结果。下面的查询会让您更接近并且需要更少的格式化客户端,但是,如果没有迭代处理,您将不会得到类似的结果集。

SELECT
    USA=CASE WHEN Country='USA' THEN StateCity ELSE NULL END,
    CANADA=CASE WHEN Country='CANADA' THEN StateCity ELSE NULL END
FROM
(
    SELECT DISTINCT Country,StateCity FROM Table WHERE Country IN('USA','CANADA')
)AS X

答案 3 :(得分:0)

出于测试目的:

CREATE TABLE dbo.Country (
    Country VARCHAR(10),
    StateCity VARCHAR(10)
);

INSERT INTO dbo.Country (Country, StateCity) VALUES ('USA', 'MO');
INSERT INTO dbo.Country (Country, StateCity) VALUES ('USA', 'LA');
INSERT INTO dbo.Country (Country, StateCity) VALUES ('USA', 'OH');
INSERT INTO dbo.Country (Country, StateCity) VALUES ('CANADA', 'Ontario');
INSERT INTO dbo.Country (Country, StateCity) VALUES ('CANADA', 'Toronto');

您可以使用以下解决方案之一:

PIVOT

- 关注

CASE(我仍在努力合并结果以摆脱NULLS)

SELECT 
    USA, 
    CANADA 
FROM 
(
    SELECT 
        CASE WHEN Country='USA' THEN StateCity END AS USA,
        CASE WHEN Country='CANADA' THEN StateCity END AS CANADA
    FROM 
        dbo.Country
) A
    GROUP BY 
        USA, 
        CANADA;