如何对Postgres中多个表的出现次数求和

时间:2014-10-27 17:30:22

标签: sql postgresql database-design count aggregate-functions

我有两张桌子

  • UK_OrderUK_Order_Item
  • F_OrderF_Order_Item

UK_Order(和F_Order)的字段为:IdorderStatusUK_Order_Item(和F_Order_Item)包含以下字段:orderIdmodelorder_quantity

我试图编写SQL以返回通过英国和F销售的不同型号的总数,但不能。到目前为止,我已经提出了:

SELECT model, SUM(order_quantity) AS quantityOrdered 
FROM uk_order_item 
WHERE orderId 
IN
(
    SELECT Id FROM uk_order WHERE orderStatus = 'Incomplete'
)
GROUP BY model

以及

SELECT model, SUM(order_quantity) AS quantitySold
FROM f_order_item 
WHERE orderId 
IN
(
    SELECT Id FROM f_order WHERE orderStatus = 'Incomplete'
)
GROUP BY model

返回例如:

Model, QuantityOrdered
Volkswagen, 3
Ford, 2
Citroen, 4
...
然后,为了找到在英国和F销售的汽车总量,我必须做一点点计算(即大众汽车公司的数量=英国大众汽车公司的数量和价格+大众汽车公司#' s' s volkwagen&# 39; s quantitySold

换句话说,我的单独查询返回为英国销售的总模型,以及F(rance) - 我会重复此查询德国,西班牙等。但有没有办法返回每个售出的模型的总数整个欧洲(英国,法国,德国等)?

1 个答案:

答案 0 :(得分:3)

数据库设计

我会重新考虑您的数据库设计。包括所有国家在内的统一表可能是一个更好的主意。因此,您可以为所有国家/地区设置单个表:

order_item 
order

只需向表格country_id添加order

更简单的查询

IN构造是不必要的复杂。更简单,更快捷:

SELECT oi.model, sum(oi.order_quantity) AS quantity_ordered 
FROM   uk_order      o
JOIN   uk_order_item oi ON oi.orderid = o.id
WHERE  o.orderstatus = 'Incomplete'
GROUP  BY 1;

虽然你有单独的表,但没有什么比添加单独的计数更简单或更快:

SELECT model, sum(quantity_ordered) AS total_quantity_ordered
FROM  (
   SELECT model, sum(order_quantity) AS quantity_ordered
   FROM   uk_order      o
   JOIN   uk_order_item oi ON oi.orderid = o.id
   WHERE  o.orderstatus = 'Incomplete'
   GROUP  BY 1

   UNION  ALL
   SELECT model, sum(order_quantity) AS quantity_ordered
   FROM   f_order       o
   JOIN   f_order_item  oi ON oi.orderid = o.id
   WHERE  o.orderstatus = 'Incomplete'
   GROUP  BY 1
   ) sub
GROUP  BY 1;

可以在汇总之前将行合并到UNION ALL的单个派生表中:

SELECT model, sum(quantity_ordered) AS total_quantity_ordered
FROM  (
   SELECT model, order_quantity AS quantity_ordered
   FROM   uk_order      o
   JOIN   uk_order_item oi ON oi.orderid = o.id
   WHERE  o.orderstatus = 'Incomplete'

   UNION  ALL
   SELECT model, order_quantity AS quantity_ordered
   FROM   f_order       o
   JOIN   f_order_item  oi ON oi.orderid = o.id
   WHERE  o.orderstatus = 'Incomplete'
   ) sub
GROUP  BY 1;

但我怀疑它会更快。

我的常设建议是在Postgres中使用CaMeL案例标识符,是否引用。让您的生活更轻松。