sql—在mysql中,我们如何在这个场景中进行透视

pvcm50d1  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(369)

我有这张table:

+----------+--------+-----+--------+--------+
| 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       |
+---------------+----------+--------------+----------+

我试图得到这个使用枢轴,但面临一个问题。我如何做到这一点,使用或不使用枢轴?
谢谢您。

jdzmm42g

jdzmm42g1#

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;

相关问题