473,778 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SELECT UNTIL ?

Hi

Im not an SQL n00b, but I'm no SQL guru...

I'd like to work out the SQL code required to achieve the following goal in pseudocode:

Grap a record
Using info from that record, add (the width) to a running total.
When the running total exceeds a certain value, stop grabbing records.

Here's a snippet of code to demonstrate the functionality that is required:
--------------------------------------------------------------------------------

ImageID ImageWidth ImageBLOB
------------------------------------------
1 60 %E$Y^HYS^YHU%^T RHT
2 60 O*&^G&*^OGBV&VB ^^&
3 120 YE%$CC%$EYYEC%$ C%$
4 200 %E$Y^HYS^YHU%^T RHT
5 60 O*&^G&*^OGBV&VB ^^&
6 120 YE%$CC%$EYYEC%$ C%$
------------------------------------------

Dim CurrentTotalWid th As Integer = 0
Dim MaxWidth As Integer = 240
Dim MaxWidthExceede d As Integer = 0

Do

If CurrentTotalWid th MaxWidth Then
MaxWidthExceede d &= MaxWidthExceede d + 1
End If

SELECT [ImageID], [ImageWidth], [ImageBLOB], FROM [tblImages]

CurrentTotalWid th = CurrentTotalWid th + [ImageWidth]

Loop Until MaxWidthExceede d = 5

--------------------------------------------------------------------------------

I don't assume that the code I have submitted is the most efficient yaddah yaddah yaddah, I'm open to suggestions to make things efficient... maybe a SELECT TOP 10 ... so that im running one query instead of ten ? etc etc

Anyways,
Thanks in advance,
Douglas
Nov 30 '06 #1
11 5707
Douglas

If I understood you properly

DECLARE @MaxWidth Integer
SET @MaxWidth = 240

SELECT [ImageID], [ImageWidth], [ImageBLOB], FROM [tblImages]
WHERE [ImageWidth]<@MaxWidth

"Douglas" <po*****@the.gr oup.so.everyone .can.learnwrote in message news:11******** ******@angel.am net.net.au...
Hi

Im not an SQL n00b, but I'm no SQL guru...

I'd like to work out the SQL code required to achieve the following goal in pseudocode:

Grap a record
Using info from that record, add (the width) to a running total.
When the running total exceeds a certain value, stop grabbing records.

Here's a snippet of code to demonstrate the functionality that is required:
------------------------------------------------------------------------------

ImageID ImageWidth ImageBLOB
------------------------------------------
1 60 %E$Y^HYS^YHU%^T RHT
2 60 O*&^G&*^OGBV&VB ^^&
3 120 YE%$CC%$EYYEC%$ C%$
4 200 %E$Y^HYS^YHU%^T RHT
5 60 O*&^G&*^OGBV&VB ^^&
6 120 YE%$CC%$EYYEC%$ C%$
------------------------------------------

Dim CurrentTotalWid th As Integer = 0
Dim MaxWidth As Integer = 240
Dim MaxWidthExceede d As Integer = 0

Do

If CurrentTotalWid th MaxWidth Then
MaxWidthExceede d &= MaxWidthExceede d + 1
End If

SELECT [ImageID], [ImageWidth], [ImageBLOB], FROM [tblImages]

CurrentTotalWid th = CurrentTotalWid th + [ImageWidth]

Loop Until MaxWidthExceede d = 5

------------------------------------------------------------------------------

I don't assume that the code I have submitted is the most efficient yaddah yaddah yaddah, I'm open to suggestions to make things efficient... maybe a SELECT TOP 10 ... so that im running one query instead of ten ? etc etc

Anyways,
Thanks in advance,
Douglas
Nov 30 '06 #2
Uri Dimant wrote:
If I understood you properly

DECLARE @MaxWidth Integer
SET @MaxWidth = 240
SELECT [ImageID], [ImageWidth], [ImageBLOB], FROM [tblImages]
WHERE [ImageWidth]<@MaxWidth
That applies the limit to each row individually. He wants to apply the
limit to a running total of rows so far.

Problem: the order of selecting rows hasn't been specified. (Insert
standard Celko "rows vs. records" rant here.) If the intention is to
select rows in ORDER BY ImageID order, then the running-total decision
logic would work as follows.

1) Select ImageID 1, its ImageWidth is 60, the running total is 60.
2) Select ImageID 2, its ImageWidth is 60, the running total is
60+60=120.
3) Select ImageID 3, its ImageWidth is 120, the running total is
60+60+120=240.
4) Select ImageID 4, its ImageWidth is 200, the running total is
60+60+120+200=4 40.

The running total has now exceeded 240, so stop selecting rows. But
here's another problem: the description of the goal says to stop
right away, but the pseudocode says to select five more rows and
then stop.

Googling (SQL "running total") turns this up as the first hit:

http://www.sqlteam.com/item.asp?ItemID=3856

which gives three solutions, one that uses cursors and two that
don't, and says (with some annoyance) that the cursor solution
was an order of magnitude faster in speed tests (but, as usual,
involves a longer block of code).
Nov 30 '06 #3
Ed
I think you are right
"Ed Murphy" <em*******@soca l.rr.comwrote in message
news:KX******** **********@torn ado.socal.rr.co m...
Uri Dimant wrote:
>If I understood you properly
DECLARE @MaxWidth Integer
SET @MaxWidth = 240
SELECT [ImageID], [ImageWidth], [ImageBLOB], FROM [tblImages]
WHERE [ImageWidth]<@MaxWidth

That applies the limit to each row individually. He wants to apply the
limit to a running total of rows so far.

Problem: the order of selecting rows hasn't been specified. (Insert
standard Celko "rows vs. records" rant here.) If the intention is to
select rows in ORDER BY ImageID order, then the running-total decision
logic would work as follows.

1) Select ImageID 1, its ImageWidth is 60, the running total is 60.
2) Select ImageID 2, its ImageWidth is 60, the running total is
60+60=120.
3) Select ImageID 3, its ImageWidth is 120, the running total is
60+60+120=240.
4) Select ImageID 4, its ImageWidth is 200, the running total is
60+60+120+200=4 40.

The running total has now exceeded 240, so stop selecting rows. But
here's another problem: the description of the goal says to stop
right away, but the pseudocode says to select five more rows and
then stop.

Googling (SQL "running total") turns this up as the first hit:

http://www.sqlteam.com/item.asp?ItemID=3856

which gives three solutions, one that uses cursors and two that
don't, and says (with some annoyance) that the cursor solution
was an order of magnitude faster in speed tests (but, as usual,
involves a longer block of code).

Nov 30 '06 #4

Hi guys, and thanks for your interest in this puzzle :)

some notes below to clarify...
--------------------------------------------------------------------------------

"Ed Murphy" <em*******@soca l.rr.comwrote in message news:KX******** **********@torn ado.socal.rr.co m...
Uri Dimant wrote:
>If I understood you properly

DECLARE @MaxWidth Integer
SET @MaxWidth = 240
SELECT [ImageID], [ImageWidth], [ImageBLOB], FROM [tblImages]
WHERE [ImageWidth]<@MaxWidth
That applies the limit to each row individually. He wants to apply the
limit to a running total of rows so far.

Problem: the order of selecting rows hasn't been specified.
--------------------------------------------------------------------------------
ok, I thought id try and strip it down to its bare essentials, but i perhaps should have mentioned...

I am SELECTing * FROM (SELECT TOP @ImageQty FROM tblImages ORDER BY NEWID() ) AS [ImageTable] ORDER BY [ImageWidth];

So i can ask for 5 images chosen at random and sorted by width.

The trouble is, that some images are panoramic, and up to 9 times wider than standard pics. Other shots are portait, and therefore a lot narrower. This causes display anomolies in the resulting html :(

if maxwidth=600

image1 could be 500 - running total=(500)
image2 could be 50 - (500+50=550, no fail)
image3 could be 75 - (550+75=625) Failcount = 1, try again 4 more times
image4 could be 250 - (550+250=800) Failcount = 2, try again 3 more times
image5 could be 50 - (550+50=600, no fail (600 is not 600 ;))
image6 could be 75 - (600+75=675) Failcount = 3, try again 2 more times
image6 could be 75 - (600+500=1100) Failcount = 4, try again 1 more times
image6 could be 75 - (600+250=850) Failcount = 5, stop.

So, requesting a FINITE qty of images will not meet the needs of the goal.

The goal is: to get as many pictures, as close to a total width of 600 as possible. (without causing server meltdown, of course ;)
--------------------------------------------------------------------------------
(Insert standard Celko "rows vs. records" rant here.)
--------------------------------------------------------------------------------
I'd like to know more about that... although, now that I have asked, I may live to regret it.
--------------------------------------------------------------------------------
If the intention is to
select rows in ORDER BY ImageID order, then the running-total decision
logic would work as follows.

1) Select ImageID 1, its ImageWidth is 60, the running total is 60.
2) Select ImageID 2, its ImageWidth is 60, the running total is
60+60=120.
3) Select ImageID 3, its ImageWidth is 120, the running total is
60+60+120=240.
4) Select ImageID 4, its ImageWidth is 200, the running total is
60+60+120+200=4 40.

The running total has now exceeded 240, so stop selecting rows. But
here's another problem: the description of the goal says to stop
right away, but the pseudocode says to select five more rows and
then stop.
--------------------------------------------------------------------------------
Get five more, each time checking to see if we can squeeze it in to the remaining value.

After that, give up, to conserve server resources.


--------------------------------------------------------------------------------
Googling (SQL "running total") turns this up as the first hit:

http://www.sqlteam.com/item.asp?ItemID=3856

which gives three solutions, one that uses cursors and two that
don't, and says (with some annoyance) that the cursor solution
was an order of magnitude faster in speed tests (but, as usual,
involves a longer block of code).
--------------------------------------------------------------------------------
i'm looking into that...

once again,
thanks for your interest
Douglas

Nov 30 '06 #5
Douglas wrote:
I am SELECTing * FROM (SELECT TOP @ImageQty FROM tblImages ORDER BY
NEWID() ) AS [ImageTable] ORDER BY [ImageWidth];

So i can ask for 5 images chosen at random and sorted by width.

The trouble is, that some images are panoramic, and up to 9 times wider
than standard pics. Other shots are portait, and therefore a lot
narrower. This causes display anomolies in the resulting html :(

if maxwidth=600

image1 could be 500 - running total=(500)
image2 could be 50 - (500+50=550, no fail)
image3 could be 75 - (550+75=625) Failcount = 1, try again 4 more times
image4 could be 250 - (550+250=800) Failcount = 2, try again 3 more times
image5 could be 50 - (550+50=600, no fail (600 is not 600 ;))
image6 could be 75 - (600+75=675) Failcount = 3, try again 2 more times
image6 could be 75 - (600+500=1100) Failcount = 4, try again 1 more times
image6 could be 75 - (600+250=850) Failcount = 5, stop.

So, requesting a FINITE qty of images will not meet the needs of the goal.

The goal is: to get as many pictures, as close to a total width of 600
as possible. (without causing server meltdown, of course ;)
Ah, much clearer than the original spec, thank you.
(Insert standard Celko "rows vs. records" rant here.)

I'd like to know more about that... although, now that I have asked, I
may live to regret it.
This pertains to all the people accustomed to e.g. Access, where
each table's records have row numbers, and default to sorting in
that order. Then they encounter any number of things in SQL that
look deceptively similar: primary keys, auto-assigned ID numbers,
or just a query without an ORDER BY that happens (this time!) to
return data in the same order it was inserted. Not to mention
views and ORDER BY (see http://www.devx.com/dbzone/Article/8048).

There's a parallel "columns vs. fields" rant - I think it pertains
to inappropriate data types and/or lack of proper check constraints.
http://www.sqlteam.com/item.asp?ItemID=3856

i'm looking into that...
Yeah, I think it'll adapt well enough to what you described above.
Nov 30 '06 #6
Hey guys,

I guess the key question for me is, can this be done entirely in SQL?

importantly, is the SQL WHILE loop suitable ? using a while command *seems* to me to be used for executing a "whole" query as part of a logic branch, not "keep picking out records while condition = true/false"

my SQL is reasonable, for most general things, but im not so sharp with the more advanced concepts

maybe i will end up having to write an asp.net.vb function that grabs a bunch of records 5 at a time and handles the logic processing side of things... [just thinking out loud]
Cheers,
Douglas

--------------------------------------------------------------------------------

"Ed Murphy" <em*******@soca l.rr.comwrote in message news:xe******** ***********@tor nado.socal.rr.c om...
Douglas wrote:
>I am SELECTing * FROM (SELECT TOP @ImageQty FROM tblImages ORDER BY
NEWID() ) AS [ImageTable] ORDER BY [ImageWidth];

So i can ask for 5 images chosen at random and sorted by width.

The trouble is, that some images are panoramic, and up to 9 times wider
than standard pics. Other shots are portait, and therefore a lot
narrower. This causes display anomolies in the resulting html :(

if maxwidth=600

image1 could be 500 - running total=(500)
image2 could be 50 - (500+50=550, no fail)
image3 could be 75 - (550+75=625) Failcount = 1, try again 4 more times
image4 could be 250 - (550+250=800) Failcount = 2, try again 3 more times
image5 could be 50 - (550+50=600, no fail (600 is not 600 ;))
image6 could be 75 - (600+75=675) Failcount = 3, try again 2 more times
image6 could be 75 - (600+500=1100) Failcount = 4, try again 1 more times
image6 could be 75 - (600+250=850) Failcount = 5, stop.

So, requesting a FINITE qty of images will not meet the needs of the goal.

The goal is: to get as many pictures, as close to a total width of 600
as possible. (without causing server meltdown, of course ;)
Ah, much clearer than the original spec, thank you.
--------------------------------------------------------------------------------
aww shucks
--------------------------------------------------------------------------------
> (Insert standard Celko "rows vs. records" rant here.)

I'd like to know more about that... although, now that I have asked, I
may live to regret it.
This pertains to all the people accustomed to e.g. Access, where
each table's records have row numbers, and default to sorting in
that order. Then they encounter any number of things in SQL that
look deceptively similar: primary keys, auto-assigned ID numbers,
or just a query without an ORDER BY that happens (this time!) to
return data in the same order it was inserted. Not to mention
views and ORDER BY (see http://www.devx.com/dbzone/Article/8048).
--------------------------------------------------------------------------------
oh yes....

i rememeber them days... its all coming back to me now hehe
--------------------------------------------------------------------------------
There's a parallel "columns vs. fields" rant - I think it pertains
to inappropriate data types and/or lack of proper check constraints.
> http://www.sqlteam.com/item.asp?ItemID=3856

i'm looking into that...
Yeah, I think it'll adapt well enough to what you described above.
Nov 30 '06 #7
Douglas,

For a limited number of images you can select all possible combinations
as follows:

DECLARE @n INT
SET @n = 5

SELECT P.Number AS Combination, N.Number
FROM
--- Numbers is a table with numbers from 0 to 9999
(SELECT Number FROM Numbers WHERE Number BETWEEN 0 AND (@n-1)) N
JOIN
(SELECT Number FROM Numbers WHERE Number BETWEEN 1 AND POWER(2,@n)) P
ON P.Number & POWER(2,N.Numbe r) 0
ORDER BY P.Number

-----------------------
Alex Kuznetsov
http://sqlserver-tips.blogspot.com/
http://sqlserver-puzzles.blogspot.com/

Nov 30 '06 #8
Douglas wrote:
I guess the key question for me is, can this be done */entirely/* in SQL?

importantly, is the SQL WHILE loop suitable ? using a while command
*seems* to me to be used for executing a "*/whole/*" query as part of a
logic branch, not "keep picking out records while condition = true/false"
Any of the previously cited examples (all of which are done entirely in
SQL) ought to be adaptable. The WHILE loop allows you to iterate over a
cursor, which lets you go through a table one row at a time. (You do
have to break out of the loop if you run out of rows.)
Nov 30 '06 #9
Douglas (po*****@the.gr oup.so.everyone .can.learn) writes:
ok, I thought id try and strip it down to its bare essentials, but i
perhaps should have mentioned...

I am SELECTing * FROM (SELECT TOP @ImageQty FROM tblImages ORDER BY
NEWID() ) AS [ImageTable] ORDER BY [ImageWidth];

So i can ask for 5 images chosen at random and sorted by width.

The trouble is, that some images are panoramic, and up to 9 times wider
than standard pics. Other shots are portait, and therefore a lot
narrower. This causes display anomolies in the resulting html :(
It's probably easiest to use a temp table/table variable for this:

DECLARE @tbl TABLE (imageid int NOT NULL PRIMARY KEY,
width int NOT NULL,
rowno int NOT NULL,
accum_width int NULL)

INSERT @tbl (imageid, width, rowno)
SELECT TOP (@ImageQty)
imageid, width, row_number(ORDE R BY width, newid())
FROM tblImages
ORDER BY newid()

UPDATE @tbl
SET accum_width = (SELECT SUM(b.width)
FROM @tbl b
WHERE b.rowno <= a.rowno)
FROM @tbl a

DELETE @tbl WHERE accum_width 600

Note: this solution presumes SQL 2005.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Nov 30 '06 #10

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

Similar topics

6
4297
by: Ben Hallert | last post by:
Hi guys, I'm trying to figure out what bone headed mistake I made on something I put together. I've got a form (named 'context') that has a variable number of select-multiple inputs on it. Based on the number of variables passed through a GET string, I want to multiply the total number of selected items for each together to see how many possible combinations the selected items are generating. The following snippet of code...
8
2182
by: Arpan | last post by:
A Form has a select list which lists all the column names of a SQL Server database table. Users will select one or more than one column from this select list & after submitting the Form, the records of only those columns that he had selected in the previous page will be displayed to him. This is the Form code: ---------------------------------------- strSQL="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tblSheet'...
9
4373
by: deko | last post by:
When doing a mail merge with Word, I can't seem to get the below (abbreviated) routine to iterate strBookmark01 -- it just uses the first name in the recordset for all 10 (or whatever) documents... Is there some other code I need to get the string to iterate with each name? Thanks in advance... Set rstOutput = db.OpenRecordset("qryMailMerge") Do Until rstOutput.EOF strBookmark01 = rstData!Name
5
3508
by: ChadDiesel | last post by:
Hello Again, I want to assign a number to each record that will be part of a shipping number. I want the number value to count up until the contract number changes. Then, I want the number to go back to 1 and start counting up again until the next contract change. For example Contract 1111111 Box 1 of 2 Number Value: 1
5
2205
by: Dio | last post by:
#!/usr/bin/env python2 from sys import stdin from select import select while 1: (rr, wr, er) = select(, , ) for fd in rr: print fd
0
4111
by: hagar | last post by:
Hi all, I have a problem which I can not understand why this is happening! Debugging this I actually see that it grabs first record then when stepping through code to the line rsImportTo.AddNew it drops first record and grabs second record and continues on no problems (but no 1st record in data set) I am reading a text file record 1 is a top of text file. see code below Private Sub CmdFetchNewData_Click() on Error Goto CmdfetchErr Dim...
22
12494
by: MP | last post by:
vb6,ado,mdb,win2k i pass the sql string to the .Execute method on the open connection to Table_Name(const) db table fwiw (the connection opened via class wrapper:) msConnString = "Data Source=" & msDbFilename moConn.Properties("Persist Security Info") = False moConn.ConnectionString = msConnString moConn.CursorLocation = adUseClient moConn.Mode = adModeReadWrite' or using default...same result
16
2748
by: Richard Maher | last post by:
Hi, I have this Applet-hosted Socket connection to my server and in an ONevent/function I am retrieving all these lovely rows from the server and inserting them into the Select-List. (The on screen appearance of the Select List grows for the first 5 rows then the scroll bar appears if there's more). So far so good. . . The problem is that none of the rows I'm inserting appear on the screen until I have RETURNed from my function; so If...
11
4511
by: Richard Maher | last post by:
Hi, I have read many of the copius entries on the subject of IE performance (or the lack thereof) when populating Select Lists. I don't mind the insert performance so much, (I get 100x120byte rows inserted/sec up to 500, and 100rows/6secs up to 3000, which isn't great but then the Row Count is clicking away for the user to see and they can hit the "cancel" button at anytime, so overall I'm happy), what really disappoints me is the...
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9464
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
10122
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...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7471
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
6722
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
5368
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4031
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
2860
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.