Link to home
Start Free TrialLog in
Avatar of Vadim Rapp
Vadim RappFlag for United States of America

asked on

Query to return set of rows with aggregate more than

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
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

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
Avatar of Vadim Rapp

ASKER

Sorry, I don't see how this will return the rows with the sum of qty being >=4
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
          )

Open in new window

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

Open in new window

Glad I could help