create table products
(
product_id varchar(20) ,
cost int
);
insert into products values ('P1',200),('P2',300),('P3',500),('P4',800);

create table customer_budget
(
customer_id int,
budget int
);

insert into customer_budget values (100,400),(200,800),(300,1500);
--MEESHO HACKERRANK ONLINE SQL TEST
--find how many products falls into customer budget along with list of products 
--In case of clash choose the less costly product

SELECT * FROM products;
SELECT * FROM customer_budget;

--Compute running sum
WITH running_sum_tbl as (
SELECT product_id , cost,
SUM(cost) OVER(ORDER BY product_id) as running_sum
FROM products 
)
, final_tbl as (
SELECT C.* ,R.*
FROM customer_budget  C
JOIN running_sum_tbl R ON  R.running_sum < C.budget
)

SELECT customer_id , budget ,COUNT(*) as Total_product,
--To order the product inside products use WITHIN GROUP (ORDER BY product_id) 
STRING_AGG(product_id,',')  WITHIN GROUP (ORDER BY product_id) as products
FROM final_tbl 
GROUP BY customer_id,budget 
by