I have stored data in DB like this:
id | week | qty | product_code | related_id |
---|---|---|---|---|
1 | 2201 | 10 | X000001 | 24 |
2 | 2202 | 14 | X000001 | 24 |
3 | 2201 | 15 | X000002 | 24 |
4 | 2202 | 25 | X000002 | 24 |
5 | 2210 | 11 | X000001 | 25 |
6 | 2244 | 22 | X000001 | 26 |
... |
I want to make an sql query with the chosen related_id to get this result: For example if i chose the related_id = 24
product_code | 2201 | 2202 | 2203 | ... |
---|---|---|---|---|
X000001 | 10 | 14 | ... | |
X000002 | 15 | 25 | ... |
I want to transform all the week values of the related_id into columns with ASC order and put the right qty in front of every (product_code, week) couple.
Thanks
I got finally a solution after a few days of sql training, i post it here, it's may help someone, special thanks for @S-Man for the motivation :)
DO
$$
DECLARE
sql text;
BEGIN
WITH latest_create_date AS (
SELECT product_code, week, MAX(create_date) AS max_create_date
FROM my_table_name
WHERE related_id = 437
GROUP BY product_code, week
)
SELECT string_agg(
DISTINCT 'SUM(CASE WHEN rop.week = ' || CAST(rop.week AS text) ||
' THEN rop.qty ELSE 0 END) AS ' || rop.week || '',
', '
) INTO sql
FROM my_table_name rop
INNER JOIN latest_create_date lcd
ON rop.product_code = lcd.product_code AND rop.week = lcd.week AND rop.create_date = lcd.max_create_date;
IF sql IS NOT NULL THEN
sql := 'SELECT product_code, ' || sql ||
' FROM my_table_name WHERE related_id = 437 GROUP BY product_code';
EXECUTE sql;
END IF;
END;
$$ LANGUAGE plpgsql;