0

我有这张桌子:

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

我试图使用枢轴来实现这一点,但遇到了问题。无论使用或不使用枢轴,我该如何做到这一点?

谢谢你。

4

1 回答 1

0

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;
于 2018-08-07T10:35:05.910 回答