是sql的新手,无法找到查询示例。
所以,我有一张桌子:
bought ( customer_name, month, year, quantity, product_name )
我想找到在特定月份EX销售最多的产品。 2014年4月
让我们说:
| Jan | April | 2014 | 7 | Watches |
| Ron | April | 2014 | 4 | Rings |
| Jan | April | 2014 | 4 | Rings |
现在我有:
SELECT product_name
FROM bought
WHERE month_bought = 'April' AND year_bought = 2014 AND
quantity_buy >= all (SELECT quantity_buy
FROM bought
WHERE month_bought = 'April' AND year_bought = 2014
);
我不确定是否/在哪里使用GROUP BY作为product_name。
答案 0 :(得分:1)
您需要汇总,因为多个客户可以购买相同的产品。这反过来建议HAVING
而不是WHERE
:
SELECT product_name
FROM bought b
WHERE month_bought = 'April' AND year_bought = 2014
GROUP BY product_name
HAVING SUM(quantity_buy) >= all (SELECT SUM(b2.quantity_buy)
FROM bought b2
WHERE b2.month_bought = b.month_bought AND
b2.year_bought = b.year_bought
GROUP BY product_name
);
还有其他方式来表达此查询。这似乎与你想写的最接近。
答案 1 :(得分:0)
如果没有进一步的测试,它应该是这样的:
SELECT product_name
FROM bought
WHERE month_bought = 'April' AND year_bought = 2014 AND
sum(quantity_buy) = (SELECT max(sum(quantity_buy)) FROM bought
WHERE month_bought = 'April' AND year_bought = 2014 group by product_name)
group by product_name;
如果以相同数量销售,这将返回多个产品。