在SQL列数据转换为行数据

时间:2015-06-24 09:28:28

标签: sql-server-2008

我有一个名为Trn_EmpRetation的表,其列是TurnOver和EmpRetension 数据如下所示

TurnOver    EmpRetension
22           199

我希望数据如下所示

Description       TotalNumber
TurnOver           22
EmpRetension       199

如何在SQL中执行此操作。

由于 巴西特。

2 个答案:

答案 0 :(得分:0)

也许这就足够了:

SELECT x.Description, x.TotalNumber FROM
(
    SELECT Description = 'TurnOver',
           TotalNumber = SUM(TurnOver)
    FROM dbo.Trn_EmpRetation
    UNION ALL 
    SELECT Description = 'EmpRetension',
           TotalNumber = SUM(EmpRetension)
    FROM dbo.Trn_EmpRetation
) x

Demo

答案 1 :(得分:0)

您可以使用UNPIVOT

DECLARE @T TABLE (TurnOver INT, EmpRetension INT);
INSERT @T VALUES (22, 199);

SELECT  uptv.[Description], uptv.TotalNumber
FROM    @T AS t
        UNPIVOT
        (   TotalNumber
            FOR [Description] IN ([Turnover], [EmpRetension])
        ) AS uptv;

如果您想要一个SUM,那么只需使用SUMGROUP BY

SELECT  uptv.[Description], TotalNumber = SUM(uptv.TotalNumber)
FROM    Trn_EmpRetation AS t
        UNPIVOT
        (   TotalNumber
            FOR [Description] IN ([Turnover], [EmpRetension])
        ) AS uptv
GROUP BY uptv.[Description];