22,207
社区成员
发帖
与我相关
我的任务
分享
--测试环境sql2000
表A
id 值
1 a
2 b
3 c
4 d
5 e
表B
id value
1 2
2 3
想要得到的结果
value 值
2 a,b
3 c,d,e
[/code……
[/Quote][code=SQL]
我补充几句哈,
value就的值就是确定我在表A要取几行值,但是如果前面已经取过,那么就过滤掉。
例如我value=2的时候,这时value为表B的第一条数据,那么我就去表B前2条数据。
value=3的时候,这时我就要在表A取三条数据,此时value=3前面存在一条数据,就是value=2,所以我就必须过滤掉前面2条数据,重第三条开始取。结果就是我想要的结果啊
-----
提示:主键都是自增的。另外不存在其他字段。
create function dbo.f_str(@value int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
select @r=isnull(@r+',','')+a.值
from (select *,tid=(select count(1) from a where id<=t.id) from a t) a
join
(select t.*,tid=isnull((select top 1 value from b where value<t.value order by value desc),0)+a.number
from b t
join master..spt_values a on a.type='P' and a.number between 1 and t.value
) b
on a.tid=b.tid
where b.value=@value
return @r
end
go
select value,dbo.f_str(value) as 值 from b group by value
/**
value 值
----------- -----------------
2 a,b
3 c,d,e
(2 行受影响)
**/
请问:josy
可以不用视图来做吗?
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[值] varchar(1))
insert [A]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e'
go
if object_id('[B]') is not null drop table [B]
go
create table [B]([id] int,[value] int)
insert [B]
select 1,2 union all
select 2,3
go
create view tb_b
as
select t.*,tid=isnull((select top 1 value from b where value<t.value order by value desc),0)+a.number
from b t
join master..spt_values a on a.type='P' and a.number between 1 and t.value
go
create function dbo.f_str(@value int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
select @r=isnull(@r+',','')+a.值
from (select *,tid=(select count(1) from a where id<=t.id) from a t) a
join tb_b b on a.tid=b.tid
where b.value=@value
return @r
end
go
select value,dbo.f_str(value) as 值 from b group by value
/**
value 值
----------- -----------------
2 a,b
3 c,d,e
(2 行受影响)
**/
--测试环境sql2000
create table a
(
id int identity(1,1),
textName varchar(30)
)
go
insert into a
select a union all
select b union all
select c union all
select d union all
select e union all
select f
go
create table b
(
id int identity(1,1),
valueName int
)
go
insert into b
select 2 union all
select 3
--想要得到的结果
value 值
2 a,b
3 c,d,e