我正在尝试编写一个查询,该查询应该每月返回最高销量的产品。有4种不同的产品。
表Product_Sales具有3个属性:Product_ID(4种类型),Purchase_ID(每种产品唯一且购买1次)和Purchase_Date:
我有一个当前查询:
SELECT MONTHNAME(Purchase_Date) as "Month", Product_ID, Count(*) as "Sales_Amount"
FROM Product_Sales
GROUP BY MONTH(Purchase_Date), MONTHNAME(Purchase_Date)
ORDER BY MONTH(Purchase_Date);
当前返回:
+------------+----------+--------------+
| Month |Product_ID| Sales_Amount |
+------------+----------+--------------+
| January | 1 | 220 |
| January | 2 | 192 |
| January | 3 | 288 |
| January | 4 | 173 |
| February | 1 | 252 |
| February | 2 | 199 |
...etc.
通过查看表格,您可以看到哪个产品每月销量最高。但是我正在尝试进行一个查询,该查询仅返回该月销售最高的产品,因此该月的名称,产品ID和该月的销售量。我一直无法使用MAX方法。我希望它返回此值:
+------------+----------+--------------+
| Month |Product_ID| Sales_Amount |
+------------+----------+--------------+
| January | 3 | 288 |
| February | 1 | 252 |
| March | 3 | 288 |
| April | 2 | 343 |
| May | 1 | 272 |
etc...
我不确定这是否需要我进行函数或子查询。
感谢任何建议或帮助!
由于您使用的是MySQL 8.0或更高版本,因此您可以使用窗口功能-
SELECT Month, Product_ID, Sales_Amount
FROM (SELECT MONTHNAME(Purchase_Date) as "Month"
,Product_ID
,Count(*) as "Sales_Amount"
,ROW_NUMBER() OVER(PARTITION BY MONTHNAME(Purchase_Date) ORDER BY MONTH(Purchase_Date) DESC) RN
FROM Product_Sales
GROUP BY MONTH(Purchase_Date), MONTHNAME(Purchase_Date)
ORDER BY MONTH(Purchase_Date))
WHERE RN = 1;