原始数据如下:
单号 日期
00001 2007/11/1
00001 2007/11/2
00001 2007/11/5
00002 2007/11/2
00002 2007/11/3
要得到如下结果:
单号 日期
00001 2007/11/1,2007/11/2,2007/11/5
00002 2007/11/2,2007/11/3
------解决方案--------------------
- SQL code
create table test(单号 varchar(100),日期 varchar(100))insert into testselect'00001','2007/11/1' unionselect'00001','2007/11/2' union select'00001','2007/11/5' unionselect'00002','2007/11/2' union select'00002','2007/11/3'gocreate function getDates(@id varchar(100))returns varchar(1000)asbegin declare @ret varchar(1000) set @ret='' select @[email protected]+日期+',' from test where [email protected] if(len(@ret)>1) set @ret=left(@ret,len(@ret)-1) return @retendgoselect 单号,dbo.getDates(单号) from testgroup by 单号drop table testdrop function dbo.getDates/*00001 2007/11/1,2007/11/2,2007/11/500002 2007/11/2,2007/11/3*/
------解决方案--------------------
- SQL code
原始数据如下: /*单号 日期 00001 2007/11/1 00001 2007/11/2 00001 2007/11/5 00002 2007/11/2 00002 2007/11/3 要得到如下结果: 单号 日期 00001 2007/11/1,2007/11/2,2007/11/5 00002 2007/11/2,2007/11/3*/create table tb(单号 varchar(8), 日期 varchar(20))insert tb select '00001', '2007/11/1' union all select '00001', '2007/11/2' union all select '00001', '2007/11/5' union all select '00002', '2007/11/2' union all select '00002', '2007/11/3'gocreate function fn_Test(@ID varchar(8))returns varchar(8000)asbegin declare @result varchar(8000) set @result='' select @[email protected]+','+日期 from tb where [email protected] return stuff(@result,1,1,'')endgoselect 单号,dbo.fn_Test(单号) from tb group by 单号drop function dbo.fn_Testdrop table tb/*单号 -------- ------------------------00001 2007/11/1,2007/11/2,2007/11/500002 2007/11/2,2007/11/3(2 row(s) affected)*/
------解决方案--------------------
- SQL code
create function dbo.Test(@billno varchar(10))returns varchar(100)ASBEGIN declare @result varchar(100) set @result='' select @[email protected]+[日期]+',' from tableName if @result<>'' set @result=left(@result,len(@result)-1) return @resultEND--使用下面的查詢可獲得結果select [單號],dbo.Test([單號]) From TableName group by [單號]