【问题标题】:How do we perform the following task in crosstab?我们如何在交叉表中执行以下任务?
【发布时间】:2014-02-17 07:04:13
【问题描述】:

ProductSales 表示例。

--表格 创建表productsales ( 国家 varchar(20), 推销员 varchar(20), 金额整数 )

--在productsales中插入几条记录 插入 productsales 值('UK','Sam',25000); ... ...

--在 plpgsql 的“交叉表”中执行的查询,而不是使用枢轴运算符。 选择推销员,英国,美国,阿联酋 来自产品销售 枢轴 - 我知道这在 plpgsql 中不起作用 ( 总和(金额) 为国家 在([英国]、[美国]、[阿联酋]) ) 作为点

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    要创建crosstab,您可以使用PostgreSQL 附带的tablefunc 模块。您需要先安装它(安装方式取决于您安装 PostgreSQL 的方式),然后创建扩展:

    CREATE EXTENSION tablefunc;
    

    有了这些,您就可以简单地进行crosstab 查询:

    SELECT * FROM crosstab($$
            /* Your normal query with your own filters (the fields must be always at the same order) */
            SELECT salesman, country, amount
            FROM productsales
            WHERE country IN ('UAE','UK','US')
            /* The ORDER is really important here */
            ORDER BY 1, 2
        $$,
        /* The values that will be crossed, notice they are ordered alphabetically */
        $$VALUES('UAE'),('UK'),('US')$$
    ) AS
    /* Here you tell which columns and types you expect */
    productsales(salesman varchar(20), uae integer, uk integer, us integer);
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多