每日一题:SQL之行转列和列转行
Python学习与数据挖掘
共 1686字,需浏览 4分钟
·
2021-12-25 21:48
+---+----------+
|id |login_date|
+---+----------+
|01 |2021-02-28|
|01 |2021-03-01|
|01 |2021-03-02|
|01 |2021-03-04|
|01 |2021-03-05|
|01 |2021-03-06|
|01 |2021-03-08|
|02 |2021-03-01|
|02 |2021-03-02|
|02 |2021-03-03|
|02 |2021-03-06|
|03 |2021-03-06|
+---+----------+
select id,
concat_ws(',',collect_list(login_date)) cw
from data
group by id;
+---+----------------------------------------------------------------------------+
|id |cw |
+---+----------------------------------------------------------------------------+
|01 |2018-02-28,2018-03-01,2018-03-02,2018-03-04,2018-03-05,2018-03-06,2018-03-08|
|02 |2018-03-01,2018-03-02,2018-03-03,2018-03-06 |
|03 |2018-03-06 |
+---+----------------------------------------------------------------------------+
以上面SQL生成的数据为基准,执行下列SQL:
select id, login_date
from t
lateral view explode(split(cw,',')) b AS login_date;
结果
+---+----------+
|id |login_date|
+---+----------+
|01 |2018-02-28|
|01 |2018-03-01|
|01 |2018-03-02|
|01 |2018-03-04|
|01 |2018-03-05|
|01 |2018-03-06|
|01 |2018-03-08|
|02 |2018-03-01|
|02 |2018-03-02|
|02 |2018-03-03|
|02 |2018-03-06|
|03 |2018-03-06|
+---+----------+
(长按三秒,即可进入)
后台已放置一份精心整理的技术干货,查看即可获取! 后台回复关键字:面试,带你进入高手如云的学习交流群! 推荐阅读
评论