我有一个数据透视表的查询,我得到了这些结果:
ItemNo |转移|周一|星期二|周三|
ItemA | 1 | 10 | 20 | 30个
ItemA | 2 | 40 | 50 | 60个
ItemA | 3 | 70 | 80 | 90个
ItemB | 1 | 100 | 110 | 120个
ItemB | 2 | 130 | 140 | 150个
ItemB | 3 | 160 | 170 | 180
然后我想在当天添加转换字段,例如' Day.Shift'
预期:
Mon.1 | Mon.2 | Mon.3 | Tue.1 |星期二|星期二| Wed.1 | Wed.2 | Wed.3 |
10 | 40 | 70 | 20 | 50 | 80 | 30 | 60 | 90 |
100 | 130 | 160 | 110 | 140 | 170 | 120 | 150 | 180 |
谢谢。
答案 0 :(得分:2)
您应该UNPIVOT
然后执行PIVOT
:
DECLARE @Test TABLE
(
ItemNo VARCHAR(32),
[Shift] INT,
Mon INT,
Tue INT,
Wed INT
)
INSERT @Test
VALUES
('ItemA', 1, 10, 20, 30),
('ItemA', 2, 40, 50, 60),
('ItemA', 3, 70, 80, 90),
('ItemB', 1, 100, 110, 120),
('ItemB', 2, 130, 140, 150),
('ItemB', 3, 160, 170, 180)
SELECT ItemNo, [Mon.1],[Mon.2],[Mon.3],[Tue.1],[Tue.2],[Tue.3],[Wed.1],[Wed.2],[Wed.3]
FROM (
SELECT ItemNo, Item + '.' + CAST([Shift] AS VARCHAR) AS Item, DayShift
FROM (
SELECT ItemNo, [Shift], Mon, Tue, Wed
FROM @Test
) p
UNPIVOT (
DayShift FOR Item IN (Mon, Tue, Wed)
) u
) s
PIVOT (
MAX(DayShift)
FOR Item IN ([Mon.1],[Mon.2],[Mon.3],[Tue.1],[Tue.2],[Tue.3],[Wed.1],[Wed.2],[Wed.3])
) p