This will list all the orderid's that need rechargingSELECT o.id AS orderid, o.customerid, o.amount, MAX(c.rechargedate) AS HighestRechargeDate, SUM(CASE WHEN c.rechargedate > GETDATE() THEN 1 ELSE 0 END ) AS RechargesRemaining, 3-SUM(CASE WHEN c.rechargedate > GETDATE() THEN 1 ELSE 0 END ) AS RechargesToDoFROM orders o INNER JOIN orderrecharges c ON c.orderid = o.idGROUP BY o.id, o.customerid, o.amountHAVING COUNT(*) < 3;
This will do one recharge; it could probably be simpler, but I am using the previous query exactly as it is to identify the orderid's that need a recharge:INSERT INTO orderrecharges (orderid, amount, rechargedate)SELECT orderid, amount, DATEADD(mm,3,HighestRechargeDate)FROM( SELECT o.id AS orderid, o.customerid, o.amount, MAX(c.rechargedate) AS HighestRechargeDate, SUM(CASE WHEN c.rechargedate > GETDATE() THEN 1 ELSE 0 END ) AS RechargesRemaining, 3-SUM(CASE WHEN c.rechargedate > GETDATE() THEN 1 ELSE 0 END ) AS RechargesToDo FROM orders o INNER JOIN orderrecharges c ON c.orderid = o.id GROUP BY o.id, o.customerid, o.amount HAVING COUNT(*) < 3) s
If you need to do 2 recharges, run it twice