我在sql中有一个包含以下数据的表:
[col1] [col2]
1 aabb
2 ccdd
3 eeff
4 gghh
1 uuii
2 oopp
3 hhjj
4 lltt
...
col1中的值始终是已知的。如何在表格中对此进行转换,其中第一列的值将是新列,如下所示:
[1] [2] [3] [4]
aabb ccdd eeff gghh
uuii oopp hhjj lltt
...
答案 0 :(得分:2)
您需要使用Row_Number
和Pivot/Conditional Aggregation
如果col1
中的值始终知道
;WITH cte
AS (SELECT Row_number()OVER(partition BY [col1] ORDER BY [col2]) rn, *
FROM Yourtable)
SELECT [1] = Max(CASE WHEN [col1] = 1 THEN [col2] END),
[2] = Max(CASE WHEN [col1] = 2 THEN [col2] END),
[3] = Max(CASE WHEN [col1] = 3 THEN [col2] END),
[4] = Max(CASE WHEN [col1] = 4 THEN [col2] END)
FROM cte
GROUP BY rn
这是一种动态方法
DECLARE @col_list VARCHAR(8000)= '',
@sql VARCHAR(8000)
SELECT @col_list = (SELECT DISTINCT ',' + Quotename([col1])
FROM Yourtable
FOR xml path (''))
SET @col_list = Stuff(@col_list, 1, 1, '')
SET @sql = 'select ' + @col_list
+ ' from (SELECT Row_number()OVER(partition BY [col1] ORDER BY [col2]) rn, *
FROM Yourtable) a pivot (max([col2]) for col1 in ('
+ @col_list + '))pv'
PRINT @sql
EXEC (@sql)