SQL行转列与列转行

时间:2022-11-08 10:44:32

1.数据集

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
+---+----------+
|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|
+---+----------+

以"连续登录"中的数据为例:

?
1
2
3
4
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:

?
1
2
3
select id, login_date
from
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|
+---+----------+

 到此这篇关于SQL行转列与列转行的文章就介绍到这了,更多相关SQL行转列与列转行内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_38037405/article/details/122083226