PostgreSQL convert columns to rows? Transpose?

前端 未结 5 1060
失恋的感觉
失恋的感觉 2020-11-28 08:50

I have a PostgreSQL function (or table) which gives me the following output:

Sl.no    username    Designation    salary   etc..
 1        A           XYZ             


        
5条回答
  •  隐瞒了意图╮
    2020-11-28 09:27

    I have a simpler approach than Erwin pointed above, that worker for me with Postgres (and I think that it should work with all major relational databases whose support SQL standard)

    You can use simply UNION instead of crosstab:

    SELECT text 'a' AS "text" UNION SELECT 'b';
    
     text
    ------
     a
     b
    (2 rows)
    

    Of course that depends on the case in which you are going to apply this. Considering that you know beforehand what fields you need, you can take this approach even for querying different tables. I.e.:

    SELECT 'My first metric' as name, count(*) as total from first_table UNION
    SELECT 'My second metric' as name, count(*) as total from second_table 
    
     name             | Total
    ------------------|--------
     My first metric  |     10
     My second metric |     20
    (2 rows)
    

    It's a more maintainable approach, IMHO. Look at this page for more information: https://www.postgresql.org/docs/current/typeconv-union-case.html

提交回复
热议问题