我有以下(这里是简化的)数据库,希望获得收入最高的月份。
发票
-id
-order_id
-已发布(时间戳)
订单
-ID
orderItems
-id
-order_id
-article_id
文章
-id
-价格
到目前为止,我得到了以下声明:
Select articles.price * orderItems.order_id as revenue, Extract(month
from invoices.issued)
FROM orderItems
INNER JOIN articles ON orderItems.article_id = articles.id
Inner JOIN orders ON orderItems.order_id = orders.id
Inner JOIN invoices ON orders.id = invoices.order_id
GROUP BY year(issued), month(issued)
Order by revenue DESC Limit 1
计算得出的收入是错误的,因为价格乘以order_id,但实际上应该乘以相应的order_id的计数。我尝试实现count(orderItems.order_id),但无法正常工作。有任何想法吗?谢谢!
答案 0 :(得分:1)
我想你想要
SELECT year(i.issued), month(i.issued), SUM(a.price) as revenue,
FROM orderItems oi JOIN
articles a
ON oi.article_id = a.id JOIN
orders o
ON oi.order_id = o.id JOIN
invoices i
ON o.id = i.order_id
GROUP BY year(i.issued), month(i.issued)
ORDER BY revenue DESC
LIMIT 1;
换句话说,这是一个简单的聚合查询。永远都不需要乘以orderid
。另外请注意,此查询引入了表别名,因此该查询更易于编写和阅读。