如何在SQL中转置行

时间:2016-10-15 09:02:07

标签: sql sql-server hive

我有一个名为" TABLE1"需要以下格式输出。如何在这种情况下使用pivot或任何内部联接来获取输出

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用动态SQL进行透视,如下所示:

CREATE TABLE TABLE1 (
    Code nvarchar(1), 
    Ind nvarchar(3), 
    Region nvarchar(10), 
    Amt decimal(17,7), 
    Currency nvarchar(3), 
    Aging nvarchar(6), 
    [Count] int
)

--create table with data you provided
INSERT INTO TABLE1 VALUES
('X','XYZ','Region1', 16882.96585, 'INR','0-30', 3),
('X','XYZ','Region2', 30831.0445, 'INR','31-60', 3),
('X','XYZ','Region3', 8759.319245, 'INR','61-90', 1),
('X','XYZ','Region4', 39070.18077, 'INR','91-180', 1)

DECLARE @sql nvarchar(max),
        @col nvarchar(max)
--here we join all column names we need with aging values
SELECT @col = (
    SELECT ','+QUOTENAME([name]+' ('+Aging+')')
    FROM TABLE1 t
    CROSS JOIN sys.columns c
    WHERE [object_id] = OBJECT_ID(N'TABLE1') AND column_id > 2 AND [name] != 'Aging'
    FOR XML PATH('')
)
--construction of dynamic query
SELECT @sql = N'
SELECT *
FROM (
    SELECT  Code, 
            Ind, 
            [Columns]+'' (''+Aging+'')'' as [Columns],
            [Values]
    FROM (
        SELECT  Code, 
                Ind, 
                CAST(Region as nvarchar(max)) Region, 
                CAST(Amt as nvarchar(max)) Amt, 
                CAST(Currency as nvarchar(max)) Currency, 
                CAST(Aging as nvarchar(max)) Aging, 
                CAST([Count] as nvarchar(max)) [Count],
                ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Aging) as RowNum
        FROM TABLE1
    ) as t
    UNPIVOT (
        [Values] FOR [Columns] IN (Region, Amt, Currency, [Count])
    ) as unp
) as d
PIVOT (
    MAX([Values]) FOR [Columns] IN ('+STUFF(@col,1,1,'')+')
) as pvt'

EXEC sp_executesql @sql

DROP TABLE TABLE1

输出:

Code    Ind Region (0-30)   Amt (0-30)      Currency (0-30) Count (0-30)    Region (31-60)  Amt (31-60)     Currency (31-60)    Count (31-60)   Region (61-90)  Amt (61-90)     Currency (61-90)    Count (61-90)   Region (91-180) Amt (91-180)    Currency (91-180)   Count (91-180)
X       XYZ Region1         16882.9658500   INR             3               Region2         30831.0445000   INR                 3               Region3         8759.3192450    INR                 1               Region4         39070.1807700   INR                 1

希望这有帮助。

如果查询的结构不会发生变化,您可以PRINT @sql然后根据需要使用查询,而无需动态SQL。