November 23, 2015 at 5:35 am
I have following data
create table TestTable (id smallint identity (1,1), Score smallint )
GO
INSERT INTO TestTable ( Score ) VALUES
( 0), ( 6 ), ( 5 ), ( 4 ), (0 ), (0 ), ( 0 ), ( 3 ), ( 0 ), (0 ), (0 ),(0);
select * from TestTable order by id desc;
-- drop table TestTable
I am required to pick number of last consecutive 0 values. As in this case there are four consecutive zeros at end of table. Please suggest optimize query for it.
DBDigger Microsoft Data Platform Consultancy.
November 23, 2015 at 6:28 am
because this looks a bit like homework, let me throw out suggestions and not the solution.
the key here is that you need to test consecutive values. to do that, you need to join the table against itself, so you can compare id=12 to id = 11, but in a set based fashion.
start with modifying your last query to join your TestTable against itself, and consider how you need to offset the join condition to compare previous rows.
Lowell
November 23, 2015 at 6:45 am
I wouldn't actually use a join.
Instead just use a condition to get values after the last non zero value. In order to do that, you need to figure how to get the last non zero value, and then use it to validate against the values in your table.
For good practices, you need to do this in a "single statement" to avoid problems of concurrency.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply