我有两个看起来像这样的表:
item ID | name | available?
和
order ID | item ID | quantity
我想选择所有可用的项目(varchar是/否),总销售量超过4。
我知道它与sum
和inner join
有关,但我无法理解它。我提出的最好的是
SELECT i."item_id", i."name", SUM(o."quantity")
FROM item i INNER JOIN orders o ON i."item_id" = o."item_id"
WHERE "available = yes" AND SUM(o."quantity") > 4
GROUP BY i."item_id"
但是我收到了错误
ORA-00979:不是GROUP BY表达式
有人可以帮助我吗?
答案 0 :(得分:1)
此查询应该有效:
SELECT i.item_id, i.name, SUM(o.quantity)
FROM item i INNER JOIN orders o ON i.item_id = o.item_id
WHERE available = "yes"
GROUP BY i.item_id,i.name
HAVING SUM(o.quantity) > 4
答案 1 :(得分:0)
你想要这样的东西:
select i.item_id, i.name, sum(o.quantity)
from item i
inner join orders o on i.item_id = o.item_id
where available = 'yes'
group by i.item_id, i.name
having sum(o.quantity) > 4
这将为您提供订购时至少4个数量的商品。除非您的订单表中包含销售信息,否则并不意味着它们会被出售。
编辑:
要查找3件或更少的商品,您可以这样做:
select i.item_id, i.name, sum(coalesce(o.quantity,0))
from item i
left join orders o on i.item_id = o.item_id
where available = 'yes'
group by i.item_id, i.name
having sum(coalesce(o.quantity,0)) < 4
SQLFiddle示例:http://sqlfiddle.com/#!4/ebb7c8/1