我正在使用一个表,其中有多个行需要枢轴转换成列.所以这个枢轴是完美的解决方案,当我需要的只是一个领域时,效果很好.我需要根据枢轴返回几个字段.以下是具体细节的伪代码:
SELECT field1,[1],[2],[3],[4] FROM ( SELECT field1,field2,(ROW_NUMBER() OVER(PARTITION BY field1 ORDER BY field2)) RowID FROM tblname ) AS SourceTable PIVOT ( MAX(field2) FOR RowID IN ([1],[4]) ) AS PivotTable;
上述语法工作出色,但是当我需要在field3,field4 ….中找到更多的信息时,该怎么办?
解决方法
使用MAX(CASE …)和GROUP BY重写:
select field1,[1] = max(case when RowID = 1 then field2 end),[2] = max(case when RowID = 2 then field2 end),[3] = max(case when RowID = 3 then field2 end),[4] = max(case when RowID = 4 then field2 end) from ( select field1,RowID = row_number() over (partition by field1 order by field2) from tblname ) SourceTable group by field1
从那里你可以添加field3,field4等