【问题标题】:sum() in postgresql is returning individual rather than aggregated valuespostgresql 中的 sum() 返回单个而不是聚合值
【发布时间】:2020-08-17 22:46:45
【问题描述】:

我无法让sum() 函数在我的数据库中工作。我正在查询表purchasesstore_id(从表stores 检索)、购买的month(+year)(存储为timestamp ,未指定时区)和sum total 月销售收入。问题是没有发生聚合,因此每笔销售的总额都被报告为给定商店的每月销售总额。我想我没有正确使用“sum()”,但我还没有找到解决方案。建议和意见表示赞赏。

SELECT --month of purchase, total sales
    purchases.store_id AS store_id, 
    TO_CHAR(timestamp, 'Month'||'YYYY') AS month,
    sum(total) AS total_sales
    FROM purchases
    GROUP BY store_id, timestamp, purchases.total
    ORDER BY month, store_id;

【问题讨论】:

    标签: sql database postgresql datetime sum


    【解决方案1】:

    您正在按timestamp 分组,而您想按月分组。

    考虑:

    SELECT
        store_id,
        date_trunc('month', timestamp) AS month,
        sum(total) AS total_sales
    FROM purchases
    GROUP BY store_id, date_trunc('month', timestamp)
    ORDER BY month, store_id;
    

    这会给您month 作为截断到该月的第一天的日期:我发现这比格式化的字符串更有意义,但如果您愿意,可以将其更改回原始的to_char() 表达式。

    请注意,PostgreSQL 还支持 GROUP BYORDER BY 子句中的位置参数,这样您就可以编写:

    SELECT
        store_id,
        date_trunc('month', timestamp) AS month,
        sum(total) AS total_sales
    FROM purchases
    GROUP BY 1, 2
    ORDER BY 2, 1;
    

    【讨论】:

    • 非常感谢!我还了解到date_trunc 可以嵌套在to_char 函数中,它可以很好地作为后端和前端对,其中第一个决定聚合和组织,第二个负责演示。
    猜你喜欢
    • 2018-11-19
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2022-01-19
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    相关资源
    最近更新 更多