Vadim Rapp
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
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
ASKER
Sorry, I don't see how this will return the rows with the sum of qty being >=4
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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
)
sorry for that, but I see you solved it.
you can even make the condition simpler:
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
Glad I could help
declare @x int
set @x = 4
select top 1 * from table1 order by id
UNION
select * from table1 where qty >= @x