MySQL - 行到列查询

时间:2017-10-22 06:35:14

标签: mysql

我有一个SQL查询问题。我目前的表格如下:

  +--------+------+-----+-----+------+
  | hostid | itemname   |  itemvalue |
  +--------+------+-----+-----+------+
  |   A    |      1     |      10    |
  +--------+------+-----+-----+------+
  |   B    |      2     |      3     |
  +--------+------+-----+-----+------+

我如何编写查询以便获得这样的输出?

  +--------+------+-----+-----+--------+------+-----+----------+
  | itemname_A    | itemvalue_A   |  itemname_B  |  itemvalue_B|
  +--------+------+-----+-----+--------+------+-----+----------+
  |        1      |      10       |       2      |     3       |
  +--------+------+-----+-----+--------+------+-----+----------+

1 个答案:

答案 0 :(得分:-1)

使用某些聚合函数可以获得所需的输出

select 
max(case when hostid = 'A' then itemname end) itemname_A,
max(case when hostid = 'A' then itemvalue end) itemvalue_A,
max(case when hostid = 'B' then itemname end) itemname_B,
max(case when hostid = 'B' then itemvalue end) itemvalue_B
from demo
  

注意它适用于hostid的固定值   DEMO