Calculating a running sum can be complex. Some databases offer direct support. Here is a method in MySQL using correlated subqueries:
select t.*
from (select t.*,
(select sum(t2.qty)
from t t2
where t2.UniqName = t.UniqName and
t2.EntDate <= t.EntDate
) as cumsum
from t
) t
where cumsum >= YOURLIMIT and cumsum - qty < YOURLIMIT;
This can even have reasonable performance, if you have an index on t(UniqName, EntDate, qty)
.
This query assumes that EntDate
is not duplicated for each UniqName
and that qty
is not NULL. If qty
can be zero or negative, you might get multiple rows.