Oracle Mysql Sqlserver 把一列轉為按逗號分割的行
阿新 • • 發佈:2018-11-22
oracle: create table str_de(name varchar(25),addre varchar(25)); insert into str_de values('xugq','北京'); insert into str_de values('xugq','陝西'); insert into str_de values('xugq','深圳'); insert into str_de values('xugq','上海'); insert into str_de values('lfn','上海'); insert into str_de values('lfn','澳門'); insert into str_de values('lfn','香港');
[email protected]>select name,listagg(addre,',') within group(order by name) address from str_de group by name; NAME ADDRESS ---------- ------------------------------ lfn 上海,澳門,香港 xugq 上海,北京,深圳,陝西 [email protected]>select name,wm_concat(addre) address from str_de group by name; NAME ADDRESS ---------- -------------------------------------------------------------------------------- lfn 上海,香港,澳門 xugq 北京,上海,深圳,陝西 MYSQL: create table str_de(name varchar(25),addre varchar(25)); insert into str_de values('xugq','北京'); insert into str_de values('xugq','陝西'); insert into str_de values('xugq','深圳'); insert into str_de values('xugq','上海'); insert into str_de values('lfn','上海'); insert into str_de values('lfn','澳門'); insert into str_de values('lfn','香港'); mysql> select name,group_concat(addre) from str_de group by name; +------+---------------------+ | name | group_concat(addre) | +------+---------------------+ | lfn | 上海,澳門,香港 | | xugq | 北京,陝西,深圳,上海 | +------+---------------------+ 2 rows in set (0.00 sec) SQLSERVER: create table str_de(name varchar(25),addre varchar(25)); insert into str_de values('xugq','北京'); insert into str_de values('xugq','陝西'); insert into str_de values('xugq','深圳'); insert into str_de values('xugq','上海'); insert into str_de values('lfn','上海'); insert into str_de values('lfn','澳門'); insert into str_de values('lfn','香港'); SELECT B.name, B.addre, substring(B.addre,1,len(B.addre)-1) FROM ( SELECT name,(SELECT addre+',' FROM str_de where name=A.name for XML PATH('')) AS addre FROM str_de A GROUP BY name )B; 需要將結果中最後一個逗號做處理. name addre addre1 lfn 上海,澳門,香港, 上海,澳門,香港 xugq 北京,陝西,深圳,上海, 北京,陝西,深圳,上海