从2个表中获取基于总销售额的前5个数据

时间:2018-11-28 08:49:03

标签: mysql mysqli

我有表格“ sales”和类似此方案的数据:

name | 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

和这样的用户表:

User    |  Pict
user a    user_a.jpg
user b    user_a.jpg
user c    user_a.jpg

如何根据每月的总销售量获得前五名用户,我尝试使用这种查询,但始终显示不正确:

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

结果应该是:

user_a.jpg | User a | 300
user_b.jpg | User b | 370
user_c.jpg | User c | 360

因此订单必须是:B,C,A cuz,基于总销售额最高。

但是输出总是这样:

user_a.jpg | User a | 300
user_a.jpg | User b | 370
user_a.jpg | User c | 360

第一列始终为user_a.jpg

1 个答案:

答案 0 :(得分:1)

您在那儿。与用户表一起加入查询,如下所示:

SELECT users.user, users.pict, total_sales
FROM (
    SELECT name, SUM(Amount) AS total_sales
    FROM sales
    WHERE Month BETWEEN 1 AND 12
    GROUP BY name
    ORDER BY total_sales
    LIMIT 5
) AS user_sales
INNER JOIN users ON user_sales.name = users.user
ORDER BY total_sales DESC

您似乎混淆了列名;您必须相应地修改以上查询。