日期:2014-05-19  浏览次数:20571 次

求一合并字段sql的语句
有表A:

ID   Name   Value
1     jim     K,
1     jim     M,
1     jim     L,
1     jim     A,
2     Kate   B,
2     Kate   D,

想得到如下结果:
ID   Name     Value
1     Jim       K,M,L,A,
2     Kate     B,D

请问那位大哥,这个该怎么做?   谢谢各位了!


------解决方案--------------------
create table 表A(ID int , Name varchar(10), Value varchar(10))
insert 表A
select 1, 'jim ', 'K, '
union all
select 1, 'jim ', 'M, '
union all
select 1, 'jim ', 'L, '
union all
select 1, 'jim ', 'A, '
union all
select 2, 'Kate ', 'A, '
union all
select 2, 'Kate ', 'D, '


CREATE FUNCTION ConStr(@id int)
returns varchar(1000)
as
begin
declare @str varchar(1000)
SET @str = ' '
SELECT @str = @str + Value FROM 表A where id = @id
return @str
end

select id , name , dbo.ConStr(id) from 表A group by id , name
------解决方案--------------------
--带符号合并行列转换

--有表t,其数据如下:
a b
1 1
1 2
1 3
2 1
2 2
3 1
--如何转换成如下结果:
a b
1 1,2,3
2 1,2
3 1

create table tb
(
a int,
b int
)
insert into tb(a,b) values(1,1)
insert into tb(a,b) values(1,2)
insert into tb(a,b) values(1,3)
insert into tb(a,b) values(2,1)
insert into tb(a,b) values(2,2)
insert into tb(a,b) values(3,1)
go

if object_id( 'pubs..f_hb ') is not null
drop function f_hb
go

--创建一个合并的函数
create function f_hb(@a int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ' '
select @str = @str + ', ' + cast(b as varchar) from tb where a = @a
set @str = right(@str , len(@str) - 1)
return(@str)
End
go

--调用自定义函数得到结果:
select distinct a ,dbo.f_hb(a) as b from tb

drop table tb

--结果
a b
----------- ------
1 1,2,3
2 1,2
3 1

(所影响的行数为 3 行)


多个前列的合并
数据的原始状态如下:
ID PR CON OP SC
001 p c 差 6
001 p c 好 2
001 p c 一般 4
002 w e 差 8
002 w e 好 7
002 w e 一般 1
===========================
用SQL语句实现,变成如下的数据
ID PR CON OPS
001 p c 差(6),好(2),一般(4)
002 w e 差(8),好(7),一般(1)

if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb
(
id varchar(10),
pr varchar(10),
con varchar(10),
op varchar(10),
sc int
)

insert into tb(ID,PR,CON,OP,SC) values( '001 ', 'p ', 'c ', '差 ', 6)
insert into tb(ID,PR,CON,OP,SC) values( '001 ', 'p ', 'c ', '好 ', 2)
insert into tb(ID,PR,CON,OP,SC) values( '001 ', 'p ', 'c ', '一般 ', 4)
insert into tb(ID,PR,CON,OP,SC) values( '002 ', 'w ', 'e ', '差 ', 8)
insert into tb(ID,PR,CON,OP,SC) values( '002 ', 'w ',