我对SQL很新,我试图回答这个问题:
产品X存在的平均订单总数是多少。
我们有订单表和订单项。订单包含多个订单项,这些订单项会再次存储product_id
。
SELECT
avg(total)
FROM
orders
WHERE
(shipment_state = 'shipped')
AND (delivery_date BETWEEN '2017-09-11' AND '2017-09-18');
是我现在所拥有的,但是我不知道如何根据另一个表(在这种情况下line_item
)获取和计算它
答案 0 :(得分:0)
您可以使用exists
:
SELECT AVG(o.total)
FROM orders o
WHERE o.shipment_state = 'shipped' AND
o.delivery_date BETWEEN '2017-09-11' AND '2017-09-18' AND
EXISTS (SELECT 1
FROM orderlines ol
WHERE ol.order_id = o.order_id AND
ol.product_id = X
);
注意:
BETWEEN
。推荐的构造是o.delivery_date >= '2017-09-11' AND o.delivery_date < '2017-09-19'
。这适用于日期和日期/时间值。