有没有办法转置这个表:
A a
A b
A c
A d
B e
B f
C g
C h
C i
到此?
A B C
a e g
b f h
c i
d
非常感谢!
答案 0 :(得分:5)
您可以使用ROW_NUMBER
和条件聚合:
WITH Cte AS(
SELECT *,
rn = ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col2)
FROM #tbl
)
SELECT
A = MAX(CASE WHEN col1 = 'A' THEN col2 END),
B = MAX(CASE WHEN col1 = 'B' THEN col2 END),
C = MAX(CASE WHEN col1 = 'C' THEN col2 END)
FROM Cte
GROUP BY rn
答案 1 :(得分:3)
<强>查询强>
DECLARE @sql AS VARCHAR(MAX);
SELECT @sql = 'WITH Cte AS(
SELECT *, rn = ROW_NUMBER() OVER(
PARTITION BY col1 ORDER BY col2
)
FROM your_table_name
) SELECT '
+ STUFF((
SELECT DISTINCT
',COALESCE(MAX(CASE col1 WHEN ''' + col1 + ''' THEN col2 END), '''') AS [' + col1 + ']'
FROM your_table_name
FOR XML PATH('')), 1, 1, '');
SELECT @sql += ' FROM cte GROUP BY rn;';
EXEC(@sql);
<强>结果强>
+---+---+---+
| A | B | C |
+---+---+---+
| a | e | g |
| b | f | h |
| c | | i |
| d | | |
+---+---+---+
Find demo here
强>