【问题标题】:Pivot table in MySQL or PostgresMySQL 或 Postgres 中的数据透视表
【发布时间】:2015-12-03 00:34:21
【问题描述】:

【问题讨论】:

    标签: mysql sql postgresql pivot-table


    【解决方案1】:

    示例数据:

    create table test (
        custname text, 
        computer numeric, 
        monitor numeric, 
        software numeric);
    
    insert into test values
    ('Alison', 345.89, 123.45, 78.78),
    ('Jason', 435.34, 158.23, 243.54);
    

    查询:

    select 
        custname "Customer", 
        unnest(array['Computer', 'Monitor', 'Software']) "Item type",
        unnest(array[computer, monitor, software]) "Amount"
    from test;
    
     Customer | Item type | Amount 
    ----------+-----------+--------
     Alison   | Computer  | 345.89
     Alison   | Monitor   | 123.45
     Alison   | Software  |  78.78
     Jason    | Computer  | 435.34
     Jason    | Monitor   | 158.23
     Jason    | Software  | 243.54
    (6 rows)
    

    如果unnest() 不可用,您可以使用union

    select custname "Customer", 'Computer' "Item type", computer "Amount" from test
    union select custname, 'Monitor', monitor from test
    union select custname, 'Sofware', software from test
    order by 1, 2;
    

    【讨论】:

    • 感谢您的回答,如果我要在 MySql 或 Redshift 中执行此操作(没有 unnest 功能),我该怎么做?
    • 太棒了!谢谢,克林:)
    • 用于生成 MySQL 代码:pivot blog;
    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多