Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*create table tab(
- week_end VARCHAR(30),
- category VARCHAR(30),
- out_of_stock FLOAT,
- delivery_lag FLOAT,
- product_deficit FLOAT,
- nostock FLOAT,
- other FLOAT);
- INSERT INTO tab VALUES ('23.01.2022', 'Equipment', 0.24, 0.02, 0.04, 0.07, 0.11),
- ('23.01.2022', 'Shoes', 0.14, 0.04, 0.04, 0.03, 0.03),
- ('23.01.2022', 'Clothing', 0.16, 0.03, 0.05, 0.06, 0.02);*/
- WITH t3 AS (
- SELECT t1.week_end, t1.category, t1.out_of_stock, t2.*
- FROM tab AS t1
- cross join lateral (
- VALUES
- (t1.delivery_lag, 'delivery_lag'),
- (t1.product_deficit, 'product_deficit'),
- (t1.nostock, 'nostock'),
- (t1.other, 'other')
- ) AS t2(d, cause1)
- ),
- t4 AS (
- SELECT *, DENSE_RANK() OVER(PARTITION BY category ORDER BY d DESC) AS r
- FROM t3
- ),
- t5 AS (
- SELECT *
- FROM t4
- WHERE r=1
- ),
- t6 AS (
- SELECT week_end, category, out_of_stock, cause1||' ('||d||')' AS cause2
- FROM t5
- )
- SELECT week_end, category, out_of_stock, STRING_AGG(cause2, ', ') AS cause
- FROM t6
- GROUP BY week_end, category, out_of_stock
Advertisement
Add Comment
Please, Sign In to add comment