我有一个名为Trn_EmpRetation的表,其列是TurnOver和EmpRetension 数据如下所示
TurnOver EmpRetension
22 199
我希望数据如下所示
Description TotalNumber
TurnOver 22
EmpRetension 199
如何在SQL中执行此操作。
由于 巴西特。
答案 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
答案 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,那么只需使用SUM
和GROUP 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];