我在SQL Server 2014中有下表。
<table>
<tr><td>ColumnName</td><td>RowOrdinal</td><td>Value</td></tr>
<tr><td>EmpName</td><td>0</td><td>John</td></tr>
<tr><td>EmpTitle</td><td>0</td><td>Engineer</td></tr>
<tr><td>EmpCity</td><td>0</td><td>Chicago</td></tr>
<tr><td>EmpName</td><td>1</td><td>Matt</td></tr>
<tr><td>EmpTitle</td><td>1</td><td>Analyst</td></tr>
<tr><td>EmpCity</td><td>1</td><td>Boston</td></tr>
</table>
基本上我需要将行转换为列(可能使用PIVOT),所以我的输出应该如下:
<table>
<tr><td>RowOrdinal</td><td>EmpName</td><td>EmpTitle</td><td>EmpCity</td></tr>
<tr><td>0</td><td>John</td><td>Engineer</td><td>Chicago</td></tr>
<tr><td>1</td><td>Matt</td><td>Analyst</td><td>Boston</td></tr>
</table>
如果可能,请提供SQL来实现此目的。感谢。
答案 0 :(得分:2)
简单PIVOT
将为您完成工作
SELECT RowOrdinal,
[EmpName],
[EmpTitle],
[EmpCity]
FROM yourtable
PIVOT (Max(Value)
FOR columnname IN([EmpName],
[EmpTitle],
[EmpCity]))pv
或使用Conditional Aggregate
SELECT RowOrdinal,
EmpName=Max(CASE WHEN ColumnName = 'EmpName' THEN Value END),
EmpTitle=Max(CASE WHEN ColumnName = 'EmpTitle' THEN Value END),
EmpCity=Max(CASE WHEN ColumnName = 'EmpCity' THEN Value END),
FROM yourtable
GROUP BY RowOrdinal