我已经在这里阅读了这个答案,{{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 |
+--------+----------+-----------+------+----+