Solved

Query to return set of rows with aggregate more than

Posted on 2014-01-25
316 Views
Can we create a query that will return the minimum set of rows, ordered by column A, where sum(column B)>=X ?  So in the following example, with X=4, it should return first and second rows.

create table table1(id int, qty int)
insert into table1 (id,qty) select 1,3
insert into table1 (id,qty) select 2,2
insert into table1 (id,qty) select 3,6
0
• 2
• 2

LVL 69

Expert Comment

ID: 39809313
It is 2 different queries but you can Union them to get a single resultset:

declare @x int
set @x = 4
select top 1 * from table1 order by id
UNION
select * from table1 where qty >= @x
0

LVL 40

Author Comment

ID: 39809372
Sorry, I don't see how this will return the rows with the sum of qty being >=4
0

LVL 142

Accepted Solution

Guy Hengel [angelIII / a3] earned 500 total points
ID: 39809478
I think you want something like this:
``````declare @x int
set @x = 4
;with data as (select t.id, t.qty, (select sum(x.qty) from yourtable x where x.id <= t.id ) sum_qty
from yourtable t
)
select * from data
where sum_qty >= @x
and sum_qty - qty < @x
``````
0

LVL 40

Author Closing Comment

ID: 39809499
Thanks; we in fact wanted not only the last row but all rows that make the total, so with little modification:

``````declare @x int
set @x = 10
;with data as (select t.id, t.qty, (select sum(x.qty) from table1 x where x.id <= t.id ) sum_qty
from table1 t
)
select * from data
where (
sum_qty <= @x
or
sum_qty - qty < @x
)
``````
0

LVL 142

Expert Comment

ID: 39809969
sorry for that, but I see you solved it.
you can even make the condition simpler:
``````declare @x int
set @x = 4
;with data as (select t.id, t.qty, (select sum(x.qty) from yourtable x where x.id <= t.id ) sum_qty
from yourtable t
)
select * from data
where sum_qty - qty < @x
``````
0

Featured Post

Suggested Solutions

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.