SQL查询;水平到垂直

时间:2013-12-05 18:58:36

标签: sql sql-server sql-server-2008 sql-server-2005 pivot

我的数据库中有这些数据:

+-------------+------------+--------------------------------------+
| resource_id | rkident_id |              stringval               |
+-------------+------------+--------------------------------------+
|          21 |         15 | Hostname1                            |
|          21 |         16 | vm-143                               |
|          21 |         17 | 91345645-1E18-4C76-B119-C14E950FB086 |
|          22 |         15 | Hostname2                            |
|          22 |         16 | vm-179                               |
|          22 |         17 | 91345645-1E18-4C76-B119-C14E950FB086 |
+-------------+------------+--------------------------------------+

但我想像这样显示:

+-------------+-------------+--------------------------------------+
| IDENTVALUE1 | IDENTVALUE2 |             IDENTVALUE3              |
+-------------+-------------+--------------------------------------+
| Hostname1   | vm-143      | 91345645-1E18-4C76-B119-C14E950FB086 |
| Hostname2   | vm-179      | 91345645-1E18-4C76-B119-C14E950FB086 |
+-------------+-------------+--------------------------------------+

请帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

这应该这样做:

SELECT
  max(CASE WHEN rkident_id = 15 THEN stringval END) IDENTVALUE1,
  max(CASE WHEN rkident_id = 16 THEN stringval END) IDENTVALUE2,
  max(CASE WHEN rkident_id = 17 THEN stringval END) IDENTVALUE3
FROM t
GROUP BY resource_id

输出:

| IDENTVALUE1 | IDENTVALUE2 |                          IDENTVALUE3 |
|-------------|-------------|--------------------------------------|
|   Hostname1 |      vm-143 | 91345645-1E18-4C76-B119-C14E950FB086 |
|   Hostname2 |      vm-179 | 91345645-1E18-4C76-B119-C14E950FB086 |

小提琴here