Query for grouping by comparing sum of value for group, stopping when quantity is reached
-1
votes
1
answer
79
views
Trying to calculate values for a FIFO report. Is there a way using SQL to group data such that you're comparing the sum of a particular value against different values for each group, including taking only part of a row if necessary?
Request: For each Item Number, order the Purchased Items in descending order by Date, and get the maximum amount such that the sum of the Quantities is = the Amount Sold for that Item Number, taking only a part of the final row if necessary to get the quantities to match. Then output a result containing ItemNumber, NumShipments, and CostSum (which is the sum of the product of CostPer and Quantity) for the remaining stock that has not been sold.
For example, consider the following schema:
CREATE TABLE MYLIB.TOTAL_ITEM_SOLD (ITEM_NUMBER VARCHAR(15) NOT NULL NOT HIDDEN , QUANTITY_SOLD DECIMAL(5, 2) NOT HIDDEN , PRIMARY KEY (ITEM_NUMBER) ) NOT VOLATILE UNIT ANY KEEP IN MEMORY NO ;
CREATE TABLE MYLIB.ITEM_PURCHASE (ITEM_NUMBER VARCHAR(15) NOT NULL NOT HIDDEN , DATE_ORDERED TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP NOT NULL NOT HIDDEN , QUANTITY DECIMAL(4, 2) NOT NULL NOT HIDDEN , COST_PER DECIMAL(10, 2) NOT NULL NOT HIDDEN , PRIMARY KEY (DATE_ORDERED, ITEM_NUMBER) ) NOT VOLATILE UNIT ANY KEEP IN MEMORY NO ;
INSERT INTO MYLIB.TOTAL_ITEM_SOLD (ITEM_NUMBER, QUANTITY_SOLD) VALUES ('APPLE', 5);
INSERT INTO MYLIB.ITEM_PURCHASE (ITEM_NUMBER, QUANTITY, COST_PER) VALUES ('APPLE', 2, 1.23);
INSERT INTO MYLIB.ITEM_PURCHASE (ITEM_NUMBER, QUANTITY, COST_PER) VALUES ('APPLE', 4, 2.34);
INSERT INTO MYLIB.ITEM_PURCHASE (ITEM_NUMBER, QUANTITY, COST_PER) VALUES ('APPLE', 2, 5.55);
Expected result:
{ITEM_NUMBER: "APPLE", QTY_REMAINING: 3, COST_SUM: 13.44}
Because 5.55+5.55+2.34 = 13.44.
Asked by Sarov
(281 rep)
Aug 4, 2023, 07:03 PM
Last activity: Aug 6, 2023, 05:43 PM
Last activity: Aug 6, 2023, 05:43 PM