SQL将行转置为列

时间:2017-10-29 05:16:09

标签: mysql transpose

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

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

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

+--------+--
| A   | B |  
+--------+--
|  1  | 2 |
+--------+--
|  10 | 3 |
+--------+--

1 个答案:

答案 0 :(得分:0)

一般来说,您所寻求的是" 支点"。然而,这需要一个小小的技巧" - 使用cross join - 允许将2列移动到2行。然后max()group by用于生成数据透视。

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE Table1
    (`hostid` varchar(1), `itemname` int, `itemvalue` int)
;

INSERT INTO Table1
    (`hostid`, `itemname`, `itemvalue`)
VALUES
    ('A', 1, 10),
    ('B', 2, 3)
;

查询1

select a, b
from (
      select 
          max(case
             when n = 1 and hostid = 'A' then itemname 
             when n = 2 and hostid = 'A' then Itemvalue 
          end) A
        ,  max(case
             when n = 1 and hostid = 'B' then itemname 
             when n = 2 and hostid = 'B' then Itemvalue 
          end) b
          , n
      from table1
      cross join (select 1 n union all select 2) n
      group by n
    ) d
;   

<强> Results

|  a | b |
|----|---|
|  1 | 2 |
| 10 | 3 |