Dynamic alternative to pivot with CASE and GROUP BY

后端 未结 5 1700
温柔的废话
温柔的废话 2020-11-22 05:28

I have a table that looks like this:

id    feh    bar
1     10     A
2     20     A
3      3     B
4      4     B
5      5     C
6      6     D
7      7              


        
5条回答
  •  温柔的废话
    2020-11-22 05:59

    I'm sorry about returning in the past, but the solution "Dynamic Crosstab" returns erroneous result table. Thus, the valN values are erroneously "aligned to the left" and they don't correspond to the column names. When the input table has "holes" in the values, e.g. "C" has val1 and val3 but not val2. This produces an error: val3 value will be ranged in the column val2 (i.e. the next free column) in the final table.

    CREATE TEMP TABLE tbl (row_name text, attrib text, val int); 
    INSERT INTO tbl (row_name, attrib, val) VALUES ('C', 'val1', 5) ('C', 'val3', 7);
    
    SELECT * FROM crosstab('SELECT row_name, attrib, val FROM tbl 
    ORDER BY 1,2') AS ct (row_name text, val1 int, val2 int, val3 int);
    
    row_name|val1|val2|val3
     C      |   5|  7 |
    

    In order to return correct cells with "holes" in the right column, the crosstab query requires a 2nd SELECT in the crosstab, something like this "crosstab('SELECT row_name, attrib, val FROM tbl ORDER BY 1,2', 'select distinct row_name from tbl order by 1')"

提交回复
热议问题