MySQL - 使用字符串行到列

时间:2016-01-17 00:33:19

标签: mysql

我已经在这里阅读了这个答案,{{3}},并且我已经能够将它应用于我的情况,直到汇总功能(第3步)。

我尝试将itemname中的行转换为以下itemvalue中行的列:

+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
|      1 | address  | 12 street |
|      2 | email    | so@gmail  |
|      3 | name     | legend    |
+--------+----------+-----------+

我应用了以下代码:

create view table_extended as (
  select
    history.*,
    case when itemname = "address" then itemvalue end as address,
    case when itemname = "email" then itemvalue end as email,
    case when itemname = "name" then itemvalue end as name
  from history
);

现在我有 table_extended

+--------+----------+-----------+-------------+----------+---------+
| hostid | itemname | itemvalue | address     | email    | name    |
+--------+----------+-----------+-------------+----------+---------+
|      1 | address  | 12 street |   12 street | NULL     | NULL    |
|      1 | email    | so@gmail  |        NULL | so@gmail | NULL    |
|      1 | name     | legend    |        NULL | NULL     | legend  |
+--------+----------+-----------+------+------+----------+---------+

第3步中,他使用sum来聚合所有值都是整数的扩展表。我尝试使用以下代码创建另一个视图,但当然这些是字符串,因此它将除hostid之外的所有行都转为0。

create view history_itemvalue_pivot as (
  select
    hostid,
    sum(address) as address,
    sum(email) as email,
    sum(name) as name
  from history_extended
  group by hostid
);

看起来像这样:

+--------+-------------+----------+---------+
| hostid | address     | email    | name    |
+--------+-------------+----------+---------+
|      1 | 0           | 0        | 0       |
+--------+----------+-----------+------+----+

如何使用NULL合并所有行以获取以下内容:

+--------+-------------+----------+---------+
| hostid | address     | email    | name    |
+--------+----------+-----------+-----------+
|      1 | 12 street   | so@gmail | legend  |
+--------+----------+-----------+------+----+

0 个答案:

没有答案