在開發過程中經常碰到要實現按照某一字段,將其它欄位中不同的值連線後顯示到一行上的需求。本人總結了以下幾種方法,在實際開發中可以參考。
建立表結構,在oracle9i上。
create table temp
(deptno int,
ename varchar(20 byte),
*** varchar(20 byte),
age varchar(20 byte)
); insert into temp values(10,'aaa','f','18');
insert into temp values(10,'bbb','f','19');
insert into temp values(10,'ccc','f','20');
insert into temp values(20,'ddd','m','21');
insert into temp values(20,'eee','m','22');
insert into temp values(20,'fff','m','23');
insert into temp values(30,'hhh','x','24');
insert into temp values(30,'ggg','x','25');
insert into temp values(30,'yyy','x','26');
insert into temp values(30,'ttt','x','27');
commit;
第一種寫法:
select distinct first_value (deptno) over (partition by deptno order by lv desc) as deptno,
first_value (ename) over (partition by deptno order by lv desc) as ename
from (select deptno, sys_connect_by_path (ename, ' ') ename,
level lv from (select deptno, ename,
lag (ename, 1, null) over (partition by deptno order by ename) ename_1
from (select deptno, ename from temp))
connect by prior ename = ename_1
order by deptno)
結果如下:
10| aaa bbb ccc
20| ddd eee fff
30| ggg hhh ttt yyy
改進後可以增加一列如下:
select distinct first_value (deptno) over (partition by deptno order by lv desc) as deptno,
first_value (***) over (partition by *** order by lv desc) as ***,
first_value (ename) over (partition by deptno order by lv desc) as ename
from (select deptno, ***, sys_connect_by_path (ename, ' ') ename, level lv
from (select deptno, ename, ***,
lag (ename, 1, null) over (partition by deptno order by ename) ename_1
from (select deptno, ename, *** from temp))
connect by prior ename = ename_1
order by deptno)
結果如下:
10|f| aaa bbb ccc
20|m| ddd eee fff
30|x| ggg hhh ttt yyy
第二種寫法:
select deptno, sys_connect_by_path (ename, ' ') as ename, ***,
sys_connect_by_path (age, ' ') as age
from (select deptno, ename, ***, age, rank () over (order by deptno)
+ row_number () over (order by deptno) rn,
row_number () over (partition by deptno order by deptno) rm
from temp) a1
where a1.rowid in (select max (a2.rowid) from temp a2 where a2.deptno = a1.deptno)
start with rm = 1
connect by prior rn = rn - 1
結果如下:
10| aaa bbb ccc|f| 18 19 20
20| ddd eee fff|m| 21 22 23
30| hhh ggg yyy ttt|x| 24 25 26 27
mysql中的多行查詢結果合併成乙個
利用函式 group concat 實現乙個id對應多個名稱時,原本為多行資料,把名稱合併成一行,如 1 10,20,20 mysql中group concat函式 完整的語法如下 group concat distinct 要連線的字段 order by asc desc 排序字段 separat...
mysql如何實現多行查詢結果合併成一行
利用函式 group concat 實現乙個id對應多個名稱時,原本為多行資料,把名稱合併成一行。其完整語法 group concat expr 該函式返回帶有來自乙個組的連線的非null值的字串結果。其完整的語法如下所示 group concat distinct expr expr order ...
MySQL多行結果合併為一行
在做乙個專案的使用者列表的時候,需要將乙個使用者的多輛車放在一行顯示,但是普通查詢出來的結果是 array 0 array id 29 user id 1 car no 234567 1 array id 21 user id 1 car no 23565 2 array id 23 user id...