C
C
cicatrix2017-11-22 16:05:25
SQL
cicatrix, 2017-11-22 16:05:25

How to check for numbering breaks in DB (SQL)?

There is a table, simplified in it there is a number field, into which numbers are received from the user.
First question: It is
required to check that the numbers are specified without gaps in the range, for example:
1, 2, 3, 4, 5 - correct
1, 3, 2, 4, 5 - correct (though not in order, but the range 1- 5 full)
1, 2, 4, 5 - not correct (there is a gap, 3 is missing)
The second question: we add the range_id field to the table and we need to count the number of continuous ranges in the loaded data and mark for each number the ordinal number of the range
1, 2, 3 , 4, 5 - one continuous range (1 - 5), put 1 everywhere
1, 2, 3, 5, 6, 7 - two continuous ranges (1-3, 5 - 7), put 1 on numbers 1-3, put 2 on 5-7
1, 3, 7, 4, 6 - three continuous ranges (1, 3-4, 6-7) set 1 for 1, 2 for 3-4, 3 for 6-7
PS all in MS-SQL

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman, 2017-11-22
@cicatrix

the first answer
is window functions the
second answer
is to write a procedure that will look through the records, look for breaks in the numbering and accumulate the range number

P
pool, 2017-11-22
@pool

second answer:
declare @i int
set @i=1
update [tbl] set [email protected],@[email protected]+case when isnull([tbl].number-(select max(t.number) from [tbl] as t where t.number<[tbl].number),1)>1 then 1 else 0 end where number in (select top 100000 number from [tbl] order by number)
select * from [tbl]
or no sort
update [ tbl] set [email protected],@[email protected]+case when isnull([tbl].number-(select max(t.number) from [tbl] as t where t.number<[tbl].number), 1)>1 then 1 else 0 end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question