473,804 Members | 3,094 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Query to return rows only when a max limit on SUM has been reached.

rod
Hello SQL gurus!

I am trying to write a query that will return a set of continguous rows
from a table, and limit the number of rows returned when a maximum
total has been reached by adding a value in one of the columns.

For example, the two columns below represent 2 columns in a table.

a 2
b 2
c 2
d 3
e 4
f 5
g 5

I want to start at, say "c", and return all the rows after it as long
as the sum of the numbers in column 2 (starting at "c") don't exceed
10. The result I'm after would be thus

c 2
d 3
e 4

....because 2 + 3 + 4 = 9 < 10

Any ideas? Many thanks.

Jul 23 '05 #1
4 10401

Try this
declare @t table(i char(10), id int)
insert into @t values('a',2)
insert into @t values('b',1)
insert into @t values('c',3)
insert into @t values('d',3)
insert into @t values('e',2)
insert into @t values('f',2)
insert into @t values('g',2)
insert into @t values('h',2)

select i, id from(
select i, id, (select sum(id) from @t where i<=T.i and i>='c') as 'Sum'
from @t T) M
where sum<=10

Madhivanan

Jul 23 '05 #2
rod
Madihivanan, many thanks for this. It works perfectly! You've made
me think more about nested sets and expanded my SQL knowledge.

Jul 23 '05 #3
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.

CREATE TABLE Foobar
(sort_order CHAR(1) NOT NULL PRIMARY KEY,
val INTEGER NOT NULL);
I want to start at, say "c", and return all the rows after it as

long as the sum of the numbers in column 2 (starting at "c") don't
exceed 10. <<

SELECT @my_starter AS start, MAX(F1.sort_ord er) AS finish
FROM Foobar AS F1
WHERE @my_starter <= F1.sort_order
AND 10 <= (SELECT SUM(F2.val)
FROM Foobar AS F2
WHERE F2.sort_order
BETWEEN @my_starter AND F1.sort_order)

Jul 23 '05 #4
rod
Thanks Joe, however this SQL doesn't produce the result I'm after. The
SQL by Madhivanan above was spot on. Thanks anyway.

Jul 23 '05 #5

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

Similar topics

3
3957
by: Mike Cocker | last post by:
Hello, I'm quite weak at PHP, so I was hoping to get some help understanding the below code. First off, I'm trying to create a "query form" that will allow me to display the results on my screen. I grabbed this code from the net hoping that I could tweak it for my needs. I'm using MySQL, PHP and IIS and they all are running fine. As the code is, it will display the form, but it won't display my result(s). Any suggestions? Cheers,
0
486
by: Jesse Sheidlower | last post by:
I'm struggling with speed issues on some queries that I would have expected to be relatively fast. Perhaps even more frustratingly, when I've tried to break these down into their components, they still execute very slowly. I've looked over all the relevant suggestions for optimization and so forth, and there's nothing I can tell that I'm missing. An example of a query is to get all the words (the cg.cw field) in a particular...
0
2013
by: unixman | last post by:
As usual, it is 2:00am, and I'm pulling my hair out, finally resorting to posting in the newsgroups for help. :) Simple problem, in theory. Given table "map": CREATE TABLE map ( entry_id int(10) unsigned NOT NULL auto_increment, piece_id int(10) unsigned NOT NULL default '0',
4
3313
by: emily_g107 | last post by:
Hi, I need to limit results in the following query type: http://www.somewhere.com/php/sql-a.php3?server=1&db=mydatabase&table=mytable&sql_query=SELECT+Field_1%2CField_2%2CField_3%2Cidno+from+mytable+where+1+and+field_1+like+%22string%22+&sql_order=&pos=1 I found a reference that says I should be able to use LIMIT x, but I don't know where/exactly how to add that to the string. Once I know what it's supposed to look like, and can...
13
1996
by: Dmitry Tkach | last post by:
Hi, everybody! Here is a weird problem, I ran into... I have two huge (80 million rows each) tables (a and b), with id as a PK on both of them and also an FK from b referencing a. When I try to run a query like: select * from a, b where a.id >= 7901288 and a.id=b.id limit 1; The query takes *forever*.
7
12092
by: Egor Shipovalov | last post by:
I'm implementing paging through search results using cursors. Is there a better way to know total number of rows under a cursor than running a separate COUNT(*) query? I think PostgreSQL is bound to know this number after the first FETCH, isn't it? On a side note, why queries using LIMIT are SO terribly slow, compared to cursors and sometimes even ones without LIMIT? Shouldn't LIMIT be internally implemented using cursor mechanism then?...
21
6986
by: CSN | last post by:
I have a pretty simple select query that joins a table (p) with 125K rows with another table (pc) with almost one million rows: select p.* from product_categories pc inner join products p on pc.product_id = p.id where pc.category_id = $category_id order by p.title
0
1313
by: oddemann | last post by:
Hi. I have a problem that I can`t find solution to. The errorlog i full of this. 01/11 15:54:15.36 sdpprim sql_agent 27772 SIGNIFICANT sqlsrvr.c 2136 The limit set by NX_SQL_QUEUE_LIMIT of 50 has been reached. FETCH Message queuing has begun. 01/11 15:54:15.49 sdpprim sql_agent 27772 SIGNIFICANT sqlsrvr.c 2220 FETCH Message queuing has stopped. Message handling has returned to normal. Max in queue was:1...
4
1865
bilibytes
by: bilibytes | last post by:
Hello i'm intrigued by what happens behind the scenes when I do a DB query to a database from php. I would like to know what is the exact life cycle of a mysql_query() I ask this question because i need to know what is the best solution to count the number of rows from a query. My query is performed to fetch records from a mysqlDb that will be displayed as a list of let's say 10 rows. If i hadn't put a sql LIMIT start, count the query...
0
9569
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
10318
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
10069
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...
0
9130
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...
0
6844
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
5503
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...
0
5636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4277
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
2975
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.