sql server - How would l write SQL to label quantities until they run out? -


i label quantities (in quantity table) using labels assigned (see label assignment table) until quantity goes 0. know done labeling particular id.

label assignment table follows:

id  |  label | quantity  1      aaa      10  1      bbb      20  2      ccc      20 

and quantity table:

id  |  total quantity  1       60  2       20 

and following result:

id  |   label    | quantity   1       aaa         10       (read reference table, remaining 50)  1       bbb         20       (read reference table, remaining 30)  1       [null]      30       (no label in reference table, remaining 0)  2       ccc         20       (read reference table, remaining 0) 

you can simple join , union operation include 'not covered' quantities:

select la.id, la.label, la.quantity label_assignment la inner join quantity q on la.id = q.id  union   select q.id, null label, q.totalquantity - la.totalquantity   quantity q inner join (    select id, sum(quantity) totalquantity    label_assignment    group id ) la on q.id = la.id , q.totalquantity > la.totalquantity  

demo here


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -