March 23, 2005 at 10:50 pm
Hi all,
I'm stuck on a problem which I'd appreciate any help. Given the following table, I want to select the row before the row where Class = '$'. So the result should give me ID 1, 4, and 6. I would like to avoid using Cursors to solve this problem as the number of rows returned will be very large.
ID Class
1 T
2 $
3 F
4 C
5 $
6 F
7 $
8 $
Thanks,
Linus
March 23, 2005 at 11:09 pm
Assume id is alwayse increase and has index on it.
scalar function use max function can help.
Like
create function fn_rowbefore$ (@id int)
returns int
as
begin
declare @ren int
select @ren = max(id) from tablename where id < @id and class != '$'
return @ren
end
select distinct dbo.fn_rowbefore$(id) from tablename where class = '$'
March 24, 2005 at 5:29 am
Thanks wz700. That certainly resolve my little problem.
Cheers,
Linus
March 24, 2005 at 6:38 am
As WZ700 said, I'm assuming that ID is a "no skip" sequential IDENTITY column...
This will "find" everything that meets your criteria all at once in a single run...
SELECT *
FROM yourtable
WHERE ID IN (--Deived table finds the correct ID's
SELECT ID-1 AS ID
FROM yourtable
WHERE Class = '$')
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply