SQL查询到网格中的输出表

时间:2015-03-02 23:24:56

标签: sql

我有一张这样的表:

| head | attribute | value |
| h1   | attr1     | val1  |
| h1   | attr2     | val2  |
| h1   | attr3     | val3  |
| h2   | attr1     | val1  |
| h2   | attr2     | val2  |
| h2   | attr3     | val3  |
| h3   | attr1     | val1  |
| h3   | attr2     | val2  |
| h3   | attr3     | val3  |

我需要以这种方式呈现它:

| head | attr1 | attr2 | attr3 |
| h1   | val1  | val2  | val3  |
| h2   | val1  | val2  | val3  |
| h3   | val1  | val2  | val3  |

最佳解决方案是什么?我可以通过head命令所有记录并从代码中解析以进行渲染。但是可以从SQL中对它进行分组吗?

1 个答案:

答案 0 :(得分:2)

declare @t table (head nchar(2), attribute nchar(5),value nchar(4))

insert @t
values ('h1','attr1','val1')
,( 'h1','attr2','val2')
,( 'h1','attr3','val3')
,( 'h2','attr1','val1')
,( 'h2','attr2','val2')
,( 'h2','attr3','val3')
,( 'h3','attr1','val1')
,( 'h3','attr2','val2')
,( 'h3','attr3','val3')

select head,[attr1],[attr2],[attr3]
from @t
pivot (max(value) for attribute in ([attr1],[attr2],[attr3])) p