日期:2014-05-18  浏览次数:20575 次

这样的报表如何实现
数据结构
table   a
idlsid   Accode     sl
001         0701         8.00

table   b  
idlsid       Bccode       sl
001             0705           3.00
001             0706           5.00

数据提取结果
idlsid       Accode             Bccode                           sl
001               0701             0705,0706                 8.00
说明:其中Accode,Bccode分别是两种单据的单据号(A表中的一张单据对应B表中的两张单据.请哪位老兄给一好的意见.



------解决方案--------------------
create table a(idlsid varchar(20), Accode varchar(20), sl decimal(10,2))
insert a select '001 ', '0701 ', 8.00

create table b(idlsid varchar(20), Bccode varchar(20), sl decimal(10,2))
insert b select '001 ', '0705 ', 3.00
union all select '001 ', '0706 ', 5.00


create function fun(@id varchar(20))
returns varchar(200)
as
begin
declare @re varchar(200)
set @re= ' '
select @re=@re+ ', '+Bccode from b where idlsid=@id

return(stuff(@re, 1, 1, ' '))
end


select *, Bccode=dbo.fun(idlsid) from a
------解决方案--------------------
用函数或游标实现。

转载一下:


/*
表 tbltest

数据如下:

列A 列B 列B
1 1 A
1 1 B
1 1 C
1 2 F
1 2 G
2 1 E
2 1 F
2 2 F

SQL文

结果

列A 列B 列B
1 1 A,B,C
1 2 F,G
2 1 E,F
2 2 F

*/

create table tbltest(列A int, 列B int,列C varchar(100))
go
insert into tbltest
select 1,1, 'A ' union all
select 1,1, 'B ' union all
select 1,1, 'C ' union all
select 1,2, 'F ' union all
select 1,2, 'G ' union all
select 2,1, 'E ' union all
select 2,1, 'F ' union all
select 2,2, 'F '


go
--写一个聚合函数:
create function dbo.fn_Merge(@F1 int,@F2 int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r= ' '
select @r=@r+ ', '+列C from tbltest where 列A=@F1 and 列B=@F2
return stuff(@r,1,1, ' ')
end
go

-- 调用函数
select 列A,列B, dbo.fn_Merge(列A,列B) as 列C from tbltest group by 列A,列B

go
drop table tbltest

go


--方法2(不用函数实现更新、查询)
--如下用于几列合并一列方法1比方法2效率高
declare @tb table(列A int,列B int,列C varchar(50),con int identity(1,1))
insert @tb
select * from ta

begin tran
while exists(select 1 from @tb)
begin
update a
set a.列C=a.列C+ ', '+b.列C
from ta a ,@tb b
where a.列A=b.列A and a.列B=b.列B and
not exists(select * from @tb where 列A=b.列A and 列B=b.列B and con <b.con )

delete b
from @tb b where not exists(select 1 from @tb where 列A=b.列A and 列B=b.列B and con <b.con)
end

select distinct 列A,列B, [列B显示]=stuff(列C,1,charindex( ', ',列C), ' '