Sample Data
Expected Data
Need to append trades under an order in a record, was able to do that using string_agg
, now I need to split the orders with a maximum value of 10. That is, the quantity for the single order should not exceed 10 , need to combine trades under a single order as much as possible as fewer amended orders are desirable.
For example: I can combine tradeid 11 and 12, the running total is 9 but when I combine tradeid 13 it becomes 12 (exceeds 10) so that needs to be in a separate order.
Am aiming to rank the trades so that I can group by orderid and rank to get the result. Using SQL Server 2016.
Script to create the sample table.
create table #order
(
orderid varchar(100),
tradeid varchar(100),
quantity int
)
insert into #order (orderid, tradeid, quantity)
values
('a', 'a1', 5),
('a', 'a2', 4),
('a', 'a3', 3),
('a', 'a4', 12),
('b', 'b1', 9),
('b', 'b2', 8),
('b', 'b3', 7)
Second example
INSERT INTO @Test
(OrderID, TradeID, Qty)
VALUES ('a', 11, 5)
, ('a', 12, 4)
, ('a', 13, 3)
, ('a', 14, 5)
, ('a', 15, 1)
, ('b', 21, 9)
, ('b', 22, 8)
, ('b', 23, 7)
Expected Result
In reality, the maximum would be about 1000 orders at 10 trades per order. A good approximate solution should be good enough.