|
| 1 | +CREATE OR REPLACE FUNCTION unpivot_products_2253() |
| 2 | +RETURNS TEXT |
| 3 | +LANGUAGE PLPGSQL |
| 4 | +AS |
| 5 | +$$ |
| 6 | +DECLARE |
| 7 | + stores_array TEXT[]; |
| 8 | + query_text TEXT := ''; |
| 9 | + store_name TEXT; |
| 10 | +BEGIN |
| 11 | + --query to find all the stores columns of the products table except product_id column |
| 12 | + SELECT ARRAY_AGG(column_name) |
| 13 | + INTO stores_array |
| 14 | + FROM information_schema.columns |
| 15 | + WHERE table_name = 'products_2253' AND column_name <> 'product_id'; |
| 16 | + |
| 17 | + -- prepare query |
| 18 | + FOREACH store_name IN ARRAY stores_array |
| 19 | + LOOP |
| 20 | + query_text := query_text || 'SELECT product_id, ''' || store_name || ''' AS store, "' || store_name ||'" FROM products_2253 WHERE "' || store_name || '" IS NOT NULL'; |
| 21 | + query_text := query_text || ' UNION '; |
| 22 | + END LOOP; |
| 23 | + |
| 24 | + query_text := LEFT(query_text,LENGTH(query_text)-6); |
| 25 | + query_text := query_text || ' ORDER BY product_id,store;'; |
| 26 | + |
| 27 | + --return the query as text |
| 28 | + RETURN query_text; |
| 29 | +END |
| 30 | +$$; |
| 31 | + |
| 32 | +SELECT unpivot_products_2253(); |
| 33 | + |
| 34 | +-- output of the function: |
| 35 | +SELECT product_id, 'LC_Store' AS store, "LC_Store" |
| 36 | +FROM products_2253 |
| 37 | +WHERE "LC_Store" IS NOT NULL |
| 38 | +UNION |
| 39 | +SELECT product_id, 'Nozama' AS store, "Nozama" |
| 40 | +FROM products_2253 |
| 41 | +WHERE "Nozama" IS NOT NULL |
| 42 | +UNION |
| 43 | +SELECT product_id, 'Shop' AS store, "Shop" |
| 44 | +FROM products_2253 |
| 45 | +WHERE "Shop" IS NOT NULL |
| 46 | +UNION |
| 47 | +SELECT product_id, 'Souq' AS store, "Souq" |
| 48 | +FROM products_2253 |
| 49 | +WHERE "Souq" IS NOT NULL |
| 50 | +ORDER BY product_id,store; |
| 51 | + |
| 52 | +--running this query manually will give us expected results |
0 commit comments