原始数据
比如有如此表结构定义:
假如查询数据如下:
select dt as "日期",bj_count as "北京", sh_count as "上海",gz_count as "广州", sz_count as "深圳"
from city_stats
order by dt---------------------------------------------------------
| 日期 | 北京 | 上海 | 广州 | 深圳 |
---------------------------------------------------------
| 2023-09-04 | 1111 | 1122 | 1133 | 1144 |
| 2023-09-05 | 2211 | 2222 | 2233 | 2244 |
| 2023-09-06 | 3311 | 3322 | 3333 | 3344 |
---------------------------------------------------------
期望效果
------------------------------------
| 日期 | 城市 | 统计 |
------------------------------------
| 2023-09-04 | 北京 | 1111 |
| 2023-09-04 | 上海 | 1122 |
| 2023-09-04 | 广州 | 1133 |
| 2023-09-04 | 深圳 | 1144 |
| 2023-09-05 | 北京 | 2211 |
| 2023-09-05 | 上海 | 2222 |
| 2023-09-05 | 广州 | 2233 |
| 2023-09-05 | 深圳 | 2244 |
| 2023-09-06 | 北京 | 3311 |
| 2023-09-06 | 上海 | 3322 |
| 2023-09-06 | 广州 | 3333 |
| 2023-09-06 | 深圳 | 3344 |
------------------------------------
解决方案
采用笛卡尔积方式"CROSS JOIN":
select s.dt as "日期", c.city_name as "城市",c.city_count as "统计"
from city_stats as s
cross join LATERAL(VALUES(1,'北京',s.bj_count),(2,'上海',s.sh_count),(3,'广州',s.gz_count),(4,'深圳',s.sz_count)
) as c (city_order,city_name,city_count)
order by s.dt, c.city_order
执行结果: