我们如何在 MySQL 中的这种情况下进行旋转

Posted

技术标签:

【中文标题】我们如何在 MySQL 中的这种情况下进行旋转【英文标题】:How can we pivot in this scenario in MySQL 【发布时间】:2018-08-07 10:07:27 【问题描述】:

我有这张桌子:

+----------+--------+-----+--------+--------+
| personId | Name   | Age | height | weight |
+----------+--------+-----+--------+--------+
| 1        | Aritra | 20  | 5.6    | 56     |
| 1        | Aritra | 30  | 5.6    | 76     |
+----------+--------+-----+--------+--------+

但要求输出是这样的:

+---------------+----------+--------------+----------+
| AttributeName | personId | Presentvalue | OldValue |
+---------------+----------+--------------+----------+
| Height        | 1        | 5.6          | 5.6      |
| weight        | 1        | 76           | 56       |
+---------------+----------+--------------+----------+

我尝试使用 pivot 来解决这个问题,但遇到了问题。使用或不使用数据透视表,我该怎么做?

谢谢。

【问题讨论】:

请避开有问题的图片 提供样本数据以获得好的答案@aritra 到目前为止你尝试过什么?您面临哪个确切问题? 【参考方案1】:

union all 可能是最简单的方法了:

select 'Height' as attributeName, personId,
       (case when age = 30 then height end) as newValue,
       (case when age = 20 then height end) as oldValue
from t 
union all
select 'Weight' as attributeName, personId,
       (case when age = 30 then weight end) as newValue,
       (case when age = 20 then weight end) as oldValue;

【讨论】:

以上是关于我们如何在 MySQL 中的这种情况下进行旋转的主要内容,如果未能解决你的问题,请参考以下文章