【问题标题】:How to "subclass" a PSQL query to increase performance/improve readability?如何“子类化” PSQL 查询以提高性能/提高可读性?
【发布时间】:2018-04-11 05:03:45
【问题描述】:

所以目前,我需要使用模板运行多个查询

SELECT SUM(quantity) 
FROM inventory_item
WHERE instance_type = (sell/buy)

现在我必须运行 5 次,每个 instance_type 一次,除了卖出/买入。

有没有办法压缩它,这样我就可以一次获得所有结果而不必运行多个查询?基本上看起来像

SELECT SUM(a.quantity) AS sell, SUM(b.quantity) AS buy
FROM inventory_item a, b
WHERE a.instance_type = 'sell'
WHERE b.instance_type = 'buy'

【问题讨论】:

    标签: sql postgresql aggregate-functions


    【解决方案1】:

    您应该使用GROUP BY 查询:

    SELECT instance_type, SUM(a.quantity) AS quantity
    FROM inventory_item a GROUP BY instance_type;
    

    这将返回如下结果:

    instance_type | quantity
    -------------------------
    sell          | 250.0
    buy           | 128.5
    

    【讨论】:

    • 你是救生员克莱门斯,工作就像一个魅力!非常感谢。如果允许,我会在 7 分钟内接受你的回答。
    猜你喜欢
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2019-12-29
    • 2013-08-03
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多