当前位置: 代码迷 >> Sql Server >> 求把多行并为一行的语句,该如何解决
  详细解决方案

求把多行并为一行的语句,该如何解决

热度:79   发布时间:2016-04-27 17:53:51.0
求把多行并为一行的语句
原来的表如下:
1 a
1 b
1 c
2 d
2 e
2 f
现在查询后希望变为
1 a,b,c
2 d,e,f



------解决方案--------------------
1. 行列转换--普通

假设有张学生成绩表(CJ)如下
Name Subject Result
张三 语文 80
张三 数学 90
张三 物理 85
李四 语文 85
李四 数学 92
李四 物理 82

想变成
姓名 语文 数学 物理
张三 80 90 85
李四 85 92 82

declare @sql varchar(4000)
set @sql = 'select Name '
select @sql = @sql + ',sum(case Subject when ' ' '+Subject+ ' ' ' then Result end) [ '+Subject+ '] '
from (select distinct Subject from CJ) as a
select @sql = @sql+ ' from test group by name '
exec(@sql)

2. 行列转换--合并

有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B:
id pid
1 1,2,3
2 1,2
3 1

创建一个合并的函数
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str= ' '
select @[email protected]+ ', '+cast(pid as varchar) from 表A where [email protected] set @str=right(@str,len(@str)-1)
return(@str)
End
go

--调用自定义函数得到结果
select distinct id,dbo.fmerg(id) from 表A
------解决方案--------------------
create table TA(id int, pid varchar(10))
insert TA
select 1, '1 ' union
select 1, '2 ' union
select 1, '3 ' union
select 2, '1 ' union
select 2, '2 ' union
select 3, '1 '


create function f1(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str= ' '
select @[email protected]+ ', '+pid from TA where [email protected]
set @str=stuff(@str,1,1, ' ')
return(@str)
end
go

--调用自定义函数得到结果
select id,dbo.f1(id) from TA group by id

------解决方案--------------------
/*
现在查询后希望变为
1, 'a,b,c '
2, 'd,e,f '

*/


create table 表名(字段1 int, 字段2 varchar(100))

insert into 表名
select 1, 'a ' union all
select 1, 'b ' union all
select 1, 'c ' union all
select 2, 'd ' union all
select 2, 'e ' union all
select 2, 'f '

go
create function fn_Merge(@id int)
returns varchar(8000)
as
begin
declare @sql varchar(8000)
set @sql= ' '
select @[email protected]+ ', '+cast(字段2 as varchar(100)) from 表名 where [email protected]
set @sql=stuff(@sql,1,1, ' ')
return(@sql)
End
go

select 字段1,dbo.fn_Merge(字段1) as 合并的值
from 表名
group by 字段1

drop table 表名
drop function fn_Merge
------解决方案--------------------


create table 表名(字段1 int, 字段2 varchar(100))

insert into 表名
select 1, 'a ' union all
select 1, 'b ' union all
select 1, 'c ' union all
select 2, 'd ' union all
select 2, 'e ' union all
select 2, 'f '

go
create function fn_Merge(@id int)
returns varchar(8000)
as
begin
declare @sql varchar(8000)
set @sql= ' '
select @[email protected]+ ', '+cast(字段2 as varchar(100)) from 表名 where [email protected]
  相关解决方案