create table one(
id int identity(1,1),
a nvarchar(10),
b int
)
go
insert into one
select 'qwe', 1 union all
select 'dsfg ', 2 union all
select N'小计1', 18 union all
select 'ger', 19 union all
select 'kuyre', 20 union all
select 'we34', 23 union all
select N'小计2', 25 union all
select 'db', 26 union all
select 'tyuq', 29 union all
select N'小计3', 35
go
-- select id from one where left(a,2) = '小计'
declare dd cursor for select id,b from one where left(a,2) = '小计'
declare @b int
declare @i int
declare @ii int
set @i = 0
set @ii =0
declare @sql varchar(8000)
set @sql = ''
open dd
FETCH NEXT FROM dd into @i,@b
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql = @sql+ 'union all select a,b,'+cast(@b as char(2)) + ' as c from one where id <= ' + cast(@i as char(2)) + ' and id > '+ cast(@ii as char(2))
set @ii = @i
FETCH NEXT FROM dd into @i,@b
END
set @sql = right(@sql, len(@sql) - 9)
exec(@sql)
CLOSE dd
DEALLOCATE dd
drop table one
/*
a b c
---------- ----------- -----------
qwe 1 18
dsfg 2 18
小计1 18 18
ger 19 25
kuyre 20 25
we34 23 25
小计2 25 25
db 26 35
tyuq 29 35
小计3 35 35
SELECT A,B,MIN(C) AS C
FROM (
select one.a,one.b,(case when one.b<= tem.b then tem.c end) as c from one ,(
select a,b,(case when a like N'小计%' then b end ) as c
from one) tem
) BB
WHERE C IS NOT NULL
GROUP BY A,B
create table dbo.one
(
id int identity(1,1),
a nvarchar(10),
b int
)
insert into one
select 'qwe', 1 union all
select 'dsfg ', 2 union all
select N'小计1', 18 union all
select 'ger', 19 union all
select 'kuyre', 20 union all
select 'we34', 23 union all
select N'小计2', 25 union all
select 'db', 26 union all
select 'tyuq', 29 union all
select N'小计3', 35
select y.oid as yid, x.oid as xid, x.b
from
(
select min(id) as oid, convert(int, replace(a, N'小计', '')) as id, min(b) as b
from one group by a having substring(a, 1,2) = N'小计'
) x
inner join
(
select min(id) as oid, convert(int, replace(a, N'小计', '')) as id, min(b) as b
from one group by a having substring(a, 1,2) = N'小计'
) y
on x.id = y.id + 1
union all
select 1 as oid, oid as id, b
from
(
select top 1 min(id) as oid, min(b) as b
from one group by a having substring(a, 1,2) = N'小计'
) z