如数据库记录如下:
id val date
1 a 2008-1-1
1 b 2008-1-2
2 c 2008-1-3
2 d 2008-1-4
1 e 2008-1-5
通过id字段汇总时,把val字段拼接起来
结果是:
id val
1 a,b,e
2 c,d
请问上述目的怎么实现?
------解决方案--------------------
- SQL code
--建立测试环境
Create Table 表(id varchar(10),amount integer,remark varchar(10))
--插入数据
insert into 表
select '1','3','aaa' union
select '1','5','bbb' union
select '1','4','ccc' union
select '2','10','pkoge' union
select '2','12','daf'
go
--测试语句
CREATE FUNCTION FunMergeCharField(@vchA varchar(10))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r=''
SELECT @[email protected]+','+remark FROM 表 WHERE [email protected]
RETURN(substring(@r,2,8000))
END
GO
select id,sum(amount) as sum,dbo.FunMergeCharField(id) as remark叠加 from 表 group by id
--删除测试环境
Drop Table 表
Drop FUNCTION FunMergeCharField
------解决方案--------------------
- SQL code
create table tb(id int, val varchar(10), date datetime)
insert into tb
select 1, 'a', '2008-1-1' union all
select 1, 'b', '2008-1-2' union all
select 2, 'c', '2008-1-3' union all
select 2, 'd', '2008-1-4' union all
select 1, 'e', '2008-1-5'
select * from tb
go
create function f_str(@id int)
returns varchar(100)
as
begin
declare @str varchar(100)
set @str=''
select @[email protected]+','+val from tb where [email protected]
set @str=stuff(@str,1,1,'')
return (@str)
end
go
select id,dbo.f_str(id) from tb group by id
/*
id
--------------
1 a,b,e
2 c,d
*/
drop function dbo.f_str
drop table tb
------解决方案--------------------
http://topic.csdn.net/u/20080123/18/9731d130-0d4b-4c11-8d89-f2c3ca331f0c.html
------解决方案--------------------
又是一个行合并的问题
应该先在论坛上找下嘛
这样就不用浪费上面达人的时间和浪费自己的可用分了 o(∩_∩)o...哈哈
------解决方案--------------------
declare @tab table
(
id int,
zimu nvarchar(20)
)
insert @tab select 1,'a'
union select 1,'b'
select * from @tab
declare @group nvarchar(4000)
set @group=''
SELECT @[email protected]+','+zimu FROM @tab where id=1
select substring(@group,2,4000)