SQL 列转行函数
Oracle:
listagg()
**listagg(字段名,’‘分隔符’) within group(order by 字段名) **
with temp as(
select 'China' nation ,'Guangzhou' city from dual union all
select 'China' nation ,'Shanghai' city from dual union all
select 'China' nation ,'Beijing' city from dual union all
select 'USA' nation ,'New York' city from dual union all
select 'USA' nation ,'Bostom' city from dual union all
select 'Japan' nation ,'Tokyo' city from dual
)
select nation,listagg(city,',') within GROUP (order by city) cities
from temp
group by nation
执行结果
NATION | CITIES |
---|---|
China | Beijing,Guangzhou,Shanghai |
Japan | Tokyo |
USA | Bostom,New York |
wm_concat()
使用wm_concat能达到同样的效果:
select nation,wm_concat(city) from temp group by nation
MySQL:
下表为 节点表:
id parent_id name
1 0 根节点
2 1 一级节点
3 1 一级节点
4 1 一级节点
5 3 二级节点
6 2 二级节点
7 4 二级节点
8 5 三级节点
9 5 三级节点
10 5 三级节点
11 6 三级节点
12 11 四级节点
13 10 四级节点
使用group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator ‘分隔符’] )
select t.name, GROUP_CONCAT(t.id ORDER BY t.`name` SEPARATOR ',') ids from tree t GROUP BY t.name
查询结果:
name | ids |
---|---|
一级节点 | 4,3,2 |
三级节点 | 11,10,9,8 |
二级节点 | 7,6,5 |
四级节点 | 13,12 |
根节点 | 1 |