------------------------------多行字段合并到一行上的SQL语句写法----------------------------------
在开发过程中经常碰到要实现按照某一字段,将其它字段中不同的值连接后显示到一行上的需求。
本人总结了一下两种方法:
CREATE TABLE dept(DEPTID int,ENAME varchar(20 BYTE),SEX varchar(20 BYTE),AGE varchar(20 BYTE));
insert into dept values(1,'张三','F','18');
insert into dept values(1,'李四','F','19');
insert into dept values(1,'王五','F','20');
insert into dept values(2,'刘六','M','21');
insert into dept values(2,'赵七','M','22');
insert into dept values(2,'曹九','M','23');
commit;
select * from dept
--第一种写法:
SELECT DISTINCT FIRST_VALUE(deptid) OVER(PARTITION BY deptid ORDER BY lv DESC) AS deptid,
FIRST_VALUE(ename) OVER(PARTITION BY deptid ORDER BY lv DESC) AS ename
FROM (SELECT deptid, SYS_CONNECT_BY_PATH(ename, ' ') ename, LEVEL lv
FROM (SELECT deptid,ename,LAG(ename, 1, NULL) OVER(PARTITION BY deptid ORDER BY ename) ename_1
FROM (SELECT deptid, ename FROM dept))
CONNECT BY PRIOR ename = ename_1
ORDER BY deptid, ename)
--Oracle中sys_connect_by_path函数用法:主要作用是可以把一个父节点下的所有子节点通过某个字符进行区分,然后连接在一个列中显示
--其中connect by是oracle中一种特有按层次递归用法,PRIOR表示上一条记录,CONNECT BY PRIOR ename=ename_1是说上一条记录的ename是本条记录的ename_1,即本记录的父亲是上一条记录。
--level是一个伪列
--结果如下:
--1 | 李四 王五 张三
--2 | 曹九 刘六 赵七
--改进后可以增加一列如下:
SELECT DISTINCT FIRST_VALUE (deptid) OVER (PARTITION BY deptid ORDER BY lv DESC) AS deptid,
FIRST_VALUE (sex) OVER (PARTITION BY sex ORDER BY lv DESC) AS sex,
FIRST_VALUE (ename) OVER (PARTITION BY deptid ORDER BY lv DESC) AS ename
FROM (SELECT deptid, sex, SYS_CONNECT_BY_PATH (ename, ' ') ename, LEVEL lv
FROM (SELECT deptid, ename, sex,
LAG (ename, 1, NULL) OVER (PARTITION BY deptid ORDER BY ename) ename_1
FROM (SELECT deptid, ename, sex FROM dept))
CONNECT BY PRIOR ename = ename_1
ORDER BY deptid)
--结果如下:
--1 |F | 李四 王五 张三
--2 |M | 曹九 刘六 赵七
--第二种写法:
SELECT deptid,SYS_CONNECT_BY_PATH(ename, ' ') AS ename,sex,SYS_CONNECT_BY_PATH(age, ' ') AS age
FROM (SELECT deptid,ename,sex,age,
RANK() OVER(ORDER BY deptid)+ROW_NUMBER() OVER(ORDER BY deptid) rn,
ROW_NUMBER() OVER(PARTITION BY deptid ORDER BY deptid) rm
FROM dept) a1
WHERE a1.ROWID IN (SELECT MAX(a2.ROWID) FROM dept a2 WHERE a2.deptid = a1.deptid)
START WITH rm = 1
CONNECT BY PRIOR rn = rn - 1
--结果如下:
--1| 张三 李四 王五|F| 18 19 20
--2| 刘六 赵七 曹九|M| 21 22 23