--生成測試資料
create
table t(department int,person varchar(20))
insert
into t select
1,'張三'
insert
into t select
1,'李四'
insert
into t select
1,'王五'
insert
into t select
2,'趙六'
insert
into t select
2,'鄧七'
insert
into t select
2,'劉八'
insert
into t select
2,'劉九'
insert
into t select
3,'劉十'
insert
into t select
3,'周十一'
go select * from t
--1.使用者定義函式
create
function f_str ( @department int )
returns varchar(8000)
asbegin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret + ',' + person
from t
where department = @department
set @ret = stuff(@ret, 1, 1, '')
return @ret
endgo
--執行
select distinct
department ,
person = dbo.f_str(department)
from t
go /*
department
person
1張三,李四,王五
2趙六,鄧七,劉八
*/--2.xml for path
select b.department ,
left(nt, len(nt) - 1) as paths
from ( select department ,
( select person + ','
from t
where department = a.department
order
by department
forxml path('')
) as nt
from t a
group
by department
) b
/* department
paths
1張三,李四,王五
2趙六,鄧七,劉八
*/--改一下上面的寫法
select department ,
person = stuff(( select ',' + person
from t t
where department = nt.department
forxml path('')
), 1, 1, '')
from t nt
group
by department
------------------------------------
--3.cte
; with result
as ( select department ,
person ,
row = row_number() over ( partition by department order
by department )
from t
), result2
as ( select department ,
cast(person as nvarchar(100)) person ,
row
from result
where row = 1
union all
select a.department ,
cast(b.person + ',' + a.person as nvarchar(100)) ,
a.row
from result a
join result2 b on a.department = b.department
and a.row = b.row + 1
) select department ,
person
from result2 a
where row = ( select
max(row)
from result
where department = a.department
) order
by department
option ( maxrecursion 0 )
-------------------------------
--刪除測試資料
drop
function f_str
drop
table t
mysql多行合併一行,一行拆分多行
資料 建表語句 drop table if exists 品牌 create table 品牌 id int 0 not null,品牌 varchar 255 character set utf8 collate utf8 general ci null default null engine i...
pandas實現多行合併一行 一行拆分多行
import pandas as pd 構造資料 data pd.dataframe 合併資料 合併前 合併後 import pandas as pd 構造資料 data pd.dataframe 拆分資料 data pinpai data 品牌 str.split expand true data...
一行變多行
xml declare tb table departmentid int,departmentcode varchar 100 insert into tb select 1,1 2 union all select 2,1 2 3 union all select 3,1 2 3 4 union...