简体   繁体   English

如何从 MySQL 中的值行创建动态列

[英]How to create dynamic columns from the value rows in MySQL

This is my table:这是我的表:

+----+-------+-----------+-------+
| id | Name  | Parameter | Value |
+----+-------+-----------+-------+
|  1 | Andy  | height    | 1.85  |
|  2 | Igal  | weight    | 56    |
|  3 | Yossi | age       | 28    |
|  4 | David | weight    |       |
|  5 | Igal  | height    | 1.9   |
|  6 | Andy  | age       | 25    |
+----+-------+-----------+-------+

This is my query:这是我的查询:

SELECT
Name,
CASE WHEN (Paramter='age') THEN Value ELSE 0 END AS AGE,
CASE WHEN (Paramter='height') THEN Value ELSE 0 END AS HEIGHT,
CASE WHEN (Paramter='weight') THEN Value ELSE 0 END AS WEIGHT
FROM
table

The result:结果:

+-------+-----+--------+--------+
| Name  | AGE | HEIGHT | WEIGTH |
+-------+-----+--------+--------+
| Andy  |   0 | 1.85   |      0 |
| Igal  |   0 | 0      |     56 |
| Yossi |  28 | 0      |      0 |
| David |   0 | 0      |        |
| Igal  |   0 | 1.9    |      0 |
| Andy  |  25 | 0      |      0 |
+-------+-----+--------+--------+

I also tried make a group by [Name], but without success.我也尝试通过 [Name] 创建一个组,但没有成功。

How do I display all data in one row for each person (Name)?如何显示在一行中的所有数据的每个人(姓名)?

Wanted table:通缉表:

+------+-----+--------+--------+ | Name | AGE | HEIGHT | WEIGTH | +------+-----+--------+--------+ | Igal | 0 | 1.9 | 56 | | Andy | 25 | 1.85 | 0 | +------+-----+--------+--------+

You want some aggregation there:你想在那里进行一些聚合:

SELECT Name,
       MAX(CASE WHEN Parameter = 'age' THEN Value END) AS AGE,
       MAX(CASE WHEN Parameter = 'height' THEN Value END) AS HEIGHT,
       MAX(CASE WHEN Parameter = 'weight' THEN Value END) AS WEIGHT
FROM table
GROUP BY Name;

I want to point out the lack of ELSE 0 .我想指出缺少ELSE 0 I see no reason to insert a 0 value for these three columns if no data is present.如果不存在数据,我认为没有理由为这三列插入0值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM