抱歉,如果这是重复的......
我有这个表(Id,Col1,Col2,..,Col3),但我希望将结果分组为这样
ID1value group,
Col1Value,
Col2Value,
Col3Value
ID2value group,
ID2Col1Value,
ID2Col2Value,
ID2Col3Value
ID3value group,
ID3Col1Value,
ID3Col2Value,
ID3Col3Value
怎么做?
我试过PIVOT
,但我认为这不会返回好结果
答案 0 :(得分:0)
听起来你想要UNPIVOT
而不是PIVOT:
DECLARE @T TABLE (ID INT, Col1 VARCHAR(15), Col2 VARCHAR(15), Col3 VARCHAR(15))
INSERT @T (ID, Col1, Col2, Col3)
VALUES
(1, 'ID1Col1Value', 'ID1Col2Value', 'ID1Col3Value'),
(2, 'ID2Col1Value', 'ID2Col2Value', 'ID2Col3Value'),
(3, 'ID3Col1Value', 'ID3Col2Value', 'ID3Col3Value');
SELECT upvt.ID,
upvt.Value
FROM @T
UNPIVOT
( Value
FOR [Group] IN ([Col1], [Col2], [Col3])
) AS upvt;
,并提供:
+----+--------------+
| ID | Value |
+----+--------------+
| 1 | ID1Col1Value |
| 1 | ID1Col2Value |
| 1 | ID1Col3Value |
| 2 | ID2Col1Value |
| 2 | ID2Col2Value |
| 2 | ID2Col3Value |
| 3 | ID3Col1Value |
| 3 | ID3Col2Value |
| 3 | ID3Col3Value |
+----+--------------+