我有两张表如下:
order_detail
Fields: order_id, name, total, quantity
order
Fields: id, order_date
对于每条记录,order_detail中有多条记录。
我正在寻找以下结果。
显示按名称分组的总和(总计)和总和(数量),其中order_date介于3/1/2015和2/29/2016之间。在这里,我想只看到按总计排序的前10项。我编写了以下查询,但我只是不断收到语法错误:
select od.name, sum(od.total) AS revenue, sum(od.quantity) as quantity FROM order_detail od
LEFT JOIN order o ON o.id=od.order_id
GROUP BY od.name ORDER BY revenue desc limit 10
WHERE (o.completed_at)::text >= '3/1/2015' and (o.completed_at)::text <= '2/29/2016'
你能用正确的语法帮助我吗?
答案 0 :(得分:3)
您需要将这些条件移至JOIN
条件。将它们置于where
条件有效地将外连接更改为内连接
您也不应将日期比较为字符串,而应将其作为日期:
select od.name,
sum(od.total) AS revenue,
sum(od.quantity) as quantity
FROM order_detail od
LEFT JOIN order o ON o.id=od.order_id
AND o.completed_at >= DATE '2015-03-01'
AND o.complated_dat <= DATE '2016-02-29'
GROUP BY od.name
ORDER BY revenue desc limit 10