473,756 Members | 5,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Query - Find block of sequential numbers

I have a database that is pre-populated with sequential part numbers.
As people reserve the parts I update a flag to show the # is no longer
available. Now they want the ability to take out a block of "x"
number of sequential part numbers - say for example 5.

If my database had the following numbers available:
101
104
105
110
111
112
113
114

It should return 110 thru 114 and then I would write an update query
to change the flags to 1 (checked out).

I have only been able to return the first "x" number of records - have
not been able to make sure they are stepped sequentially - with the
following:

SELECT ID_ITEM From PARTNO_CHKOUT_S PECIAL M Where (Select Count(*)
FROM PARTNO_CHKOUT_S PECIAL N
WHERE N.ID_ITEM <= M.ID_ITEM) >= 0 AND TYPE_REC=1 AND
FLAG_CHECKED_OU T=0 {maxrows 5}

The above would return 101, 104, 105, 110, 111

I tried using an (N.ID_ITEM+1)-M.ID_ITEM=0 to try stepping and get
errors, probably incorrect syntax. Can I do this in an SQL statement?
Jul 20 '05 #1
6 12709
"Jenn L" <jm******@dorne r.com> wrote in message
news:61******** *************** ***@posting.goo gle.com...
I have a database that is pre-populated with sequential part numbers.
As people reserve the parts I update a flag to show the # is no longer
available. Now they want the ability to take out a block of "x"
number of sequential part numbers - say for example 5.

If my database had the following numbers available:
101
104
105
110
111
112
113
114

It should return 110 thru 114 and then I would write an update query
to change the flags to 1 (checked out).

I have only been able to return the first "x" number of records - have
not been able to make sure they are stepped sequentially - with the
following:

SELECT ID_ITEM From PARTNO_CHKOUT_S PECIAL M Where (Select Count(*)
FROM PARTNO_CHKOUT_S PECIAL N
WHERE N.ID_ITEM <= M.ID_ITEM) >= 0 AND TYPE_REC=1 AND
FLAG_CHECKED_OU T=0 {maxrows 5}

The above would return 101, 104, 105, 110, 111

I tried using an (N.ID_ITEM+1)-M.ID_ITEM=0 to try stepping and get
errors, probably incorrect syntax. Can I do this in an SQL statement?


CREATE TABLE PartNumbersAvai lable
(
part_number INT NOT NULL PRIMARY KEY
)

INSERT INTO PartNumbersAvai lable (part_number)
VALUES (101)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (104)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (105)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (110)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (111)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (112)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (113)
INSERT INTO PartNumbersAvai lable (part_number)
VALUES (114)

-- All part numbers P where there doesn't exist a part number P+1
-- Broken out of the next query for clarity
CREATE VIEW NoConsecutivePa rtNumbers (part_number)
AS
SELECT P1.part_number
FROM PartNumbersAvai lable AS P1
LEFT OUTER JOIN
PartNumbersAvai lable AS P2
ON P2.part_number = P1.part_number + 1
WHERE P2.part_number IS NULL

-- All part number sequences
CREATE VIEW PartNumberSeque nces
(first_consecut ive, last_consecutiv e, sequence_length )
AS
SELECT MIN(part_number ),
last_consecutiv e,
last_consecutiv e - MIN(part_number ) + 1
FROM (SELECT P1.part_number,
MIN(P2.part_num ber) AS last_consecutiv e
FROM PartNumbersAvai lable AS P1
LEFT OUTER JOIN
NoConsecutivePa rtNumbers AS P2
ON P2.part_number >= P1.part_number
GROUP BY P1.part_number) AS P
GROUP BY last_consecutiv e

SELECT *
FROM PartNumberSeque nces
ORDER BY first_consecuti ve

first_consecuti ve last_consecutiv e sequence_length
101 101 1
104 105 2
110 114 5

-- longest sequences
SELECT *
FROM PartNumberSeque nces
WHERE sequence_length = (SELECT MAX(sequence_le ngth)
FROM PartNumberSeque nces)

first_consecuti ve last_consecutiv e sequence_length
110 114 5

--
JAG
Jul 20 '05 #2
Hi Jenn,

I'm not clear what you want. In general, if I have a complicated
UPDATE, I like to use UPDATE FROM. I first select the items that I
want and save it in a temp table. Then JOIN using the UPDATE FROM.

Something like:
Select top 5 ID_ITEM
Into #T
From PARTNO_CHKOUT_S PECIAL
Order by ID_ITEM Descending

Update PARTNO_CHKOUT_S PECIAL
Set Flag=1
From PARTNO_CHKOUT_S PECIAL a
Join #T b
On a.ID_ITEM=b.ID_ ITEM

Which can also be rewritten as:
Update PARTNO_CHKOUT_S PECIAL
Set Flag=1
From
(Select top 5 ID_ITEM From PARTNO_CHKOUT_S PECIAL Order by ID_ITEM
Descending) b
On PARTNO_CHKOUT_S PECIAL.ID_ITEM= b.ID_ITEM

jm******@dorner .com (Jenn L) wrote in message news:<61******* *************** ****@posting.go ogle.com>...
I have a database that is pre-populated with sequential part numbers.
As people reserve the parts I update a flag to show the # is no longer
available. Now they want the ability to take out a block of "x"
number of sequential part numbers - say for example 5.

If my database had the following numbers available:
101
104
105
110
111
112
113
114

It should return 110 thru 114 and then I would write an update query
to change the flags to 1 (checked out).

I have only been able to return the first "x" number of records - have
not been able to make sure they are stepped sequentially - with the
following:

SELECT ID_ITEM From PARTNO_CHKOUT_S PECIAL M Where (Select Count(*)
FROM PARTNO_CHKOUT_S PECIAL N
WHERE N.ID_ITEM <= M.ID_ITEM) >= 0 AND TYPE_REC=1 AND
FLAG_CHECKED_OU T=0 {maxrows 5}

The above would return 101, 104, 105, 110, 111

I tried using an (N.ID_ITEM+1)-M.ID_ITEM=0 to try stepping and get
errors, probably incorrect syntax. Can I do this in an SQL statement?

Jul 20 '05 #3
Thank you both for your quick responses!

John - I tried doing the temporary table but wasn't able to. I
neglected to mention my database is EMS/RMS and I don't have rights to
create a table, only update the one existing table. I can update and
select via standard SQL queries but am limited in other functions.
There will be thousands of part numbers in this table so I'm not sure
what my best approach would be (an array of used or available numbers
may cripple the page).

Louis - The update is easy especially if they want to take one number
for one special job. The problem is engineers want numbers in sequence.
For example, they need 25 sequential part numbers in the 75xxxx series,
somehow I would have to query the table to find 750200 thru 750224 were
available before doing the update. The logic of stepping through to see
if I have the sequence of numbers available is the tough part.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #4
"Jennifer Lisser" <je************ *@dorner.com> wrote in message
news:40******** *************@n ews.frii.net...
Thank you both for your quick responses!

John - I tried doing the temporary table but wasn't able to. I
neglected to mention my database is EMS/RMS and I don't have rights to
create a table, only update the one existing table. I can update and
select via standard SQL queries but am limited in other functions.
There will be thousands of part numbers in this table so I'm not sure
what my best approach would be (an array of used or available numbers
may cripple the page).

Louis - The update is easy especially if they want to take one number
for one special job. The problem is engineers want numbers in sequence.
For example, they need 25 sequential part numbers in the 75xxxx series,
somehow I would have to query the table to find 750200 thru 750224 were
available before doing the update. The logic of stepping through to see
if I have the sequence of numbers available is the tough part.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


The solution I offered does not use a temp table. The one table I created
was meant to simply be a stand-in for the table in your database that
has available part numbers. Simply substitute your table name in the
code provided and all should be fine.

--
JAG
Jul 20 '05 #5
Jennifer Lisser (je************ *@dorner.com) writes:
John - I tried doing the temporary table but wasn't able to. I
neglected to mention my database is EMS/RMS and I don't have rights to
create a table, only update the one existing table. I can update and
select via standard SQL queries but am limited in other functions.
There will be thousands of part numbers in this table so I'm not sure
what my best approach would be (an array of used or available numbers
may cripple the page).


In MS SQL Server everyone has the rights to create temp tables.

Now you mention EMS/RMS that I don't know what it is, but reviewing your
attempt to a query, I see that inlucdes syntax ("maxrows 5") which is
not legal in SQL Server. And Microsoft SQL Server is what this group is
devoted to.

In any case, you might have misunderstood the purpose of the CREATE
TABLE statement in John's posting. It is customary when you ask a question
to provide CREATE TABLE statements for the tables involved, and INSERT
statements with sample data. This increases your chances to get a good
reply. Now, the great thing with John, is that he actually does the
work for you. So from John you get a tested script which proves that
you get the desired result. But you still need to transform into your
database.

Now, John solution used views, and if you don't have privileges to
create views, you can try this query, still using his table:

SELECT *
FROM (SELECT first_consecuti ve = MIN(part_number ), last_consecutiv e,
length = last_consecutiv e - MIN(part_number ) + 1
FROM (SELECT P1.part_number,
MIN(P2.part_num ber) AS last_consecutiv e
FROM PartNumbersAvai lable AS P1
LEFT JOIN (SELECT P1.part_number
FROM PartNumbersAvai lable AS P1
LEFT JOIN PartNumbersAvai lable AS P2
ON P2.part_number = P1.part_number + 1
WHERE P2.part_number IS NULL) AS P2
ON P2.part_number >= P1.part_number
GROUP BY P1.part_number) AS P
GROUP BY last_consecutiv e) AS P
WHERE length >= 5
ORDER BY first_consecuti ve

Here I have only expanded John's views into derived tables.

Whether EMS/RMS supports derived tables I don't know, but at least
this is a feature that is in ANSI-SQL, and not proprietary to MS SQL Server.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #6
"Erland Sommarskog" <so****@algonet .se> wrote in message news:Xn******** **************@ 127.0.0.1...
Jennifer Lisser (je************ *@dorner.com) writes:
John - I tried doing the temporary table but wasn't able to. I
neglected to mention my database is EMS/RMS and I don't have rights to
create a table, only update the one existing table. I can update and
select via standard SQL queries but am limited in other functions.
There will be thousands of part numbers in this table so I'm not sure
what my best approach would be (an array of used or available numbers
may cripple the page).
In MS SQL Server everyone has the rights to create temp tables.

Now you mention EMS/RMS that I don't know what it is, but reviewing your
attempt to a query, I see that inlucdes syntax ("maxrows 5") which is
not legal in SQL Server. And Microsoft SQL Server is what this group is
devoted to.

In any case, you might have misunderstood the purpose of the CREATE
TABLE statement in John's posting. It is customary when you ask a question
to provide CREATE TABLE statements for the tables involved, and INSERT
statements with sample data. This increases your chances to get a good
reply. Now, the great thing with John, is that he actually does the
work for you. So from John you get a tested script which proves that
you get the desired result. But you still need to transform into your
database.


And this time around, you've done the work for me. Many thanks!
Glad I never miss reading an Erland post.

Warm regards,
John
Now, John solution used views, and if you don't have privileges to
create views, you can try this query, still using his table:

SELECT *
FROM (SELECT first_consecuti ve = MIN(part_number ), last_consecutiv e,
length = last_consecutiv e - MIN(part_number ) + 1
FROM (SELECT P1.part_number,
MIN(P2.part_num ber) AS last_consecutiv e
FROM PartNumbersAvai lable AS P1
LEFT JOIN (SELECT P1.part_number
FROM PartNumbersAvai lable AS P1
LEFT JOIN PartNumbersAvai lable AS P2
ON P2.part_number = P1.part_number + 1
WHERE P2.part_number IS NULL) AS P2
ON P2.part_number >= P1.part_number
GROUP BY P1.part_number) AS P
GROUP BY last_consecutiv e) AS P
WHERE length >= 5
ORDER BY first_consecuti ve

Here I have only expanded John's views into derived tables.

Whether EMS/RMS supports derived tables I don't know, but at least
this is a feature that is in ANSI-SQL, and not proprietary to MS SQL Server.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2362
by: aj70000 | last post by:
This is my query select ano,max(date),a_subject from MY_TAB where table_name='xyz' and ano=877 group by a_subject,ano order by a_subject ANO max(Date) A_Subject 877 2005-01-20 00:00:00.000 Subject_1 877 1900-01-01 00:00:00.000 Subject_2 877 2004-12-20 00:00:00.000 Subject_3
3
358
by: James | last post by:
Hi all, I am trying to write a query to do the following in SQL server but am struggling: I have a table with a int number field in it and I want to find out the lowest unused number in the table. Unfortunately, the numbers are not necesarily sequential (due to deletes). So I may have the following records:
4
2658
by: Orion | last post by:
Hi, This is kind of last minute, I have a day and a half left to figure this out. I'm working on a project using ms-sqlserver. We are creating a ticket sales system, as part of the system, I need to be able to do a search for specific tickets withing price ranges, different locations within the theaters, etc. etc. My problem is in the search one of the criteria is to search for a group of seats together. For example let's say...
1
2490
by: Alex Satrapa | last post by:
I have a table from which I'm trying to extract certain information. For historical reasons, we archive every action on a particular thing ('thing' is identified, funnily enough, by 'id'). So the only way to find out the current state of a particular combination of attributes is to "select distinct on (id, ...) ... order by date desc". In the examples below, I've taken real output from psql and done a global search/replace on various...
7
9605
by: Melissa | last post by:
I'm trying to create a function that I can put in a query field that will consecutively number the records returned by the query starting at 1 and will start at 1 each time the query is run. So far I have the function shown below which doesn't work. If Reset is True then all I get is 1 in every field and if Reset is False, the numbering does not start at 1 each time the query is run. Can someone show me a function that works. Function...
8
3724
by: Maxi | last post by:
There is a lotto system which picks 21 numbers every day out of 80 numbers. I have a table (name:Lotto) with 22 fields (name:Date,P1,P2....P21) Here is the structure and sample data: "Date","P1","P2","P3","P4","P5","P6","P7","P8","P9","P10","P11","P12","P13","P14","P15","P16","P17","P18","P19","P20","P21" 1/1/2005,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 1/2/2005,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
4
25509
by: Mahesh BS | last post by:
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
6
3807
by: sara | last post by:
I hope someone can help with this. Our director wants to have a report that will have the departments (Retail stores) across the top, stores down the side and the RANKING of the YTD dept sales within the chain in the cell. Store/Dept 1 2 3 4 B 8 1 5 2 R 1 3 2 6 (etc.)
1
6233
by: Vinod Sadanandan | last post by:
A Roadmap To Query Tuning ============================ For each SQL statement, there are different approaches that could be used to retrieve the required data. Optimization is the process of choosing the most efficient way to retrieve this data based upon the evaluation of a number of different criteria. The CBO bases optimization choices on pre-gathered table and index statistics while the RBO makes it's decisions based on a set of ...
0
9287
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9886
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8723
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7259
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6542
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3817
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2677
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.