Re: Query to find amissing number
- From: jbrock@xxxxxxxxx (John Brock)
- Date: Fri, 14 Jul 2006 16:50:38 +0000 (UTC)
In article <e969ls$f0n$1@xxxxxxxxxxxxxxxxx>,
John Brock <jbrock@xxxxxxxxx> wrote:
In article <e957qq$8u$1@xxxxxxxxxxxxxxxxxxxxxxxxx>,
Mahesh BS <mahesh.bs@xxxxxxxxxxxx> wrote:
Hello,
I need to write a query to find out a set of missing number in a given
sequence.
Eg : a Column in some table has the following data
Col1
1
2
3
4
5
6
8
9
10
Here I need to write a query to find out that number 7 is missing in the
given sequence.
One possible solution is by using any loop. But I am looking out if the same
can be achieved using any query.
This should work:
select a.Col1 from MyTable a
where not exists
(select b.Col1 from MyTable b where a.Col1 - 1 = b.Col1)
go
Actually the above doesn't return the full list of numbers that
you want, it only alerts you to the location of the gaps in your
sequence, giving you a quick way to determine if any gaps exist.
(Quick if Col1 is indexed that is -- otherwise not so quick).
However by calling a related query (note "+" rather than "-"):
select a.Col1 from MyTable a
where not exists
(select b.Col1 from MyTable b where a.Col1 + 1 = b.Col1)
go
you can get enough information to figure out how big the gaps are,
and therefore what numbers the gaps contain. You are still going
to need a loop to examine the results of the two queries, but if
the number of rows involved is large and the number of gaps is
small this might (perhaps!) be more efficient than looping through
the entire table.
I don't think there is any way to just return the list of missing
numbers directly from a query. SQL queries work by operating on
a set of input rows to produce a set of output rows. Since the
number of missing rows in a sequence is completely arbitrary, I
don't how SQL could accomplish the necessary transformation from
input to output (although SQL has features I've never used, and
maybe one of them can do this).
--
John Brock
jbrock@xxxxxxxxx
.
- References:
- Query to find amissing number
- From: Mahesh BS
- Re: Query to find amissing number
- From: John Brock
- Query to find amissing number
- Prev by Date: Re: Round-off of a float column
- Next by Date: Re: Query to find amissing number
- Previous by thread: Re: Query to find amissing number
- Next by thread: Re: Query to find amissing number
- Index(es):
Relevant Pages
|