我有表格“ sales”和类似此方案的数据:
User | Amount| Month
user a 100 1
user b 240 1
user c 120 1
user a 200 2
user b 130 2
user c 240 2
如何根据每月的总销售量获得前五名用户,我尝试使用这种查询,但始终显示错误
SELECT TOP10 USER,
SUM(amount) amount
FROM sales LIMIT 10
WHERE MONTH BETWEEN 1 AND 12
GROUP BY sales
ORDER BY 2 DESC
结果应该是:
User a | 300
User b | 370
User c | 360
因此订单必须为:B,C,A
答案 0 :(得分:1)
您可以在GROUP BY
上进行User
,并使用SUM(amount)
获取每个用户的total_sales
。现在,只需按total_sales
的降序顺序对结果集进行排序,即可首先获得最高的销售额。
如果您只想获得前10名,我们可以使用LIMIT 10
。
SELECT User,
SUM(amount) AS total_sales
FROM sales
WHERE MONTH BETWEEN 1 AND 12
GROUP BY User
ORDER BY total_sales DESC
LIMIT 10
答案 1 :(得分:1)
您可以在下面尝试
SELECT USER, SUM(amount) amount
FROM sales
WHERE MONTH BETWEEN 1 AND 12
GROUP BY USER
ORDER BY amount DESC