Pregunta

I have a mysql table with ID, UniqName,Category, EntDate, Qty.

I have to find the EntDate for each UniqName when the sum of Qty in a 'Category' goes beyond a set limit.

I am a beginner in SQL and am stumped by this report requirement.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top