【方法一 運用臨時表】
if object_id('tempdb..#item') is not null
drop table #item
create table #item
(id int identity(1,1),
groupindex int default 0,
[name] varchar(20)
)insert into #item(groupindex ,[name])
select 1, 'aaa'
union all
select 1, 'bbb'
union all
select 2, '111'
union all
select 2, '222'
-- 放入臨時表
if object_id('tempdb..#t') is not null
drop table #t
select groupindex, [name] = cast([name] as varchar(500)) -- 字段長度改為500
into #t
from #item
order by groupindex, [name]
-- 更新臨時表(逐行累加)
declare @groupindex int, @name varchar(500)
update #t set
@name = (case when @groupindex = groupindex then @name + ', ' + [name] else [name] end),
@groupindex = groupindex,
[name] = @name
-- update後的效果
select * from #t
-- 取[name]最大記錄
select groupindex, max([name]) as [name] from #t group by groupindex
-- 刪除臨時表
drop table #t
drop table #item
go【方法二 用for xml path】(只適用於sql2005以上版本)
參考資料: 靈活運用sql server for xml path
if object_id('tempdb..#item') is not null
drop table #item
create table #item
(id int identity(1,1),
groupindex int default 0,
[name] varchar(20)
)insert into #item(groupindex ,[name])
select 1, 'aaa'
union all
select 1, 'bbb'
union all
select 2, '111'
union all
select 2, '222'
-- groupby前
select a.groupindex,
(select name + ',' from #item b where b.groupindex =a.groupindex for xml path('')) as name
from #item a
-- groupby後( 當然也可以用distinct )
select a.groupindex, (select name + ',' from #item b where b.groupindex =a.groupindexfor xml path('')) as name
from #item a
group by a.groupindex
-- 處理去最後的逗號(,)
select g.groupindex, left(g.name, len(g.name)-1) as name
from
(select a.groupindex, (select name + ',' from #item b where b.groupindex =a.groupindex for xml path('')) as name
from #item a
group by a.groupindex) g
go【方法三:用函式】
if object_id('item') is not null
drop table item
create table item
(id int identity(1,1),
groupindex int default 0,
[name] varchar(20)
)insert into item(groupindex ,[name])
select 1, 'aaa'
union all
select 1, 'bbb'
union all
select 2, '111'
union all
select 2, '222'
goif object_id('dbo.f_str')>0
drop function dbo.f_str
gocreate function f_str
(@groupindex int
)returns varchar(1000)
asbegin
declare @r varchar(1000)
select @r = isnull(@r+',', '') + name
from item
where groupindex = @groupindex
return @r
endgo
select distinct groupindex, dbo.f_str(groupindex) name from item
drop table item
drop function f_str
SQL一列多行字串分組合併
最近工作遇到如下資料 需要合併後只剩下兩行的資料,普通的group by 是不能實現的。如圖 利用如下sql 即可實現需求 如圖 利用 stuff 函式實現分拆合併操作 select teachername,trainingcentername stuff select trainingcenter...
sql 分組字段合併
insert into 表 select 中國 北京 insert into 表 select 中國 上海 insert into 表 select 中國 浙江 insert into 表 select 美國 紐約 insert into 表 select 美國 華盛頓 insert into 表 ...
mysql合併分組 MYSQL 分組合併函式
mysql中group concat函式 完整的語法如下 group concat distinct 要連線的字段 order by asc desc 排序字段 separator 分隔符 基本查詢 mysql select from aa id name 1 10 1 20 1 20 2 20 3...