I'm having trouble doing a pivot in PostgreSQL 12. I have to work with a table which is constructed awkwardly. This is a similar table to what I created (just for simple representaion)-
CREATE TABLE test(Product_num INT, SN INT, Attribute VARCHAR(100), Value DECIMAL, Note VARCHAR(50) );
The next step was to import a CSV file using the COPY function-
COPY public.test from 'C:\File Location\test.csv' DELIMITER ',' csv HEADER;
I get a table with more than 30k rows which looks like-
Product_num | SN | Attribute | Value | Note |
100 9225 Unit sold 50 USA
100 9225 Unit price 4.99
100 9225 Num_boxes 2.5
101 9226 Unit sold 1 GER
101 9226 Unit price 920
101 9226 Num_boxes 2
I want to get a table which is like the next table-
Product_num | SN | Unit Sold | Unit price | Num_boxes | Note
100 | 9225 | 50 | 4.99 | 2.5 | USA
101 | 9226 | 1 | 920 | 2 | GER
I tried several methods including crosstab() and also tried to aggregate few of the columns but I encountered some issues. The table has some issues that need to be taken into consideration-
- The attribute column is not identical for every SN- Meaning every SN has different attributes, some identical and some not.
- There are a lot of null values.
- There are a lot of 0 values.
I hope I managed to explain myself as good as possible Thanks