[英]SQL: converting columns to rows
I currently have a table that looks like this:我目前有一个看起来像这样的表:
date ---- x ---- y ---- z
2020----- 2 ---- 4 ---- 8
2018 ---- 3 ---- 3 ---- 2
2019 ---- 1 ---- 6 ---- 0
I like to rotate this table meaning that the columns become rows like this:我喜欢旋转这个表,这意味着列变成这样的行:
date ---- metric ---- value
2020 ---- x ---- 2
2018 ---- x ---- 3
2019 ---- x ---- 1
2020 ---- y ---- 4
2018 ---- y ---- 3
2019 ---- y ---- 6
2020 ---- z ---- 8
2018 ---- z ---- 2
2019 ---- z ---- 0
If it was in python, I could do it using the pivote() or t() function.如果是在 python 中,我可以使用 pivote() 或 t() 函数来完成。 However, I am not sure how to do it with SQL.但是,我不确定如何使用 SQL 执行此操作。 Could you please help me with that?你能帮我解决这个问题吗?
Thanks!谢谢!
A canonical method is union all
:一个规范的方法是union all
:
select date, 'x' as metric, x as value from t union all
select date, 'y' as metric, y as value from t union all
select date, 'z' as metric, z as value from t;
Some databases support lateral joins, which simplifies this -- and is a bit faster.一些数据库支持横向连接,这简化了这一点——而且速度更快一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.