MySQL:用COUNT()对总金额进行排序

MySQL: Rank the total total amount with COUNT()

编辑:我想用 COUNT()

排名

我对客户的每一个订单进行了查看。在下一步中,我编写了一个查询来计算客户购买的总金额。 现在我想根据客户的总购买量对客户进行排名。

我写了这个查询:

SELECT u.m_name, SUM(u.num * u.price) AS total,
(SELECT COUNT(*)
FROM v_sales AS x
WHERE x.m_id = u.m_id
AND (SELECT SUM(s1.num * s1.price) FROM v_sales AS s1 WHERE s1.m_id = x.m_id)
>
(SELECT SUM(s2.num * s2.price) FROM v_sales AS s2 WHERE s2.m_id = x.m_id)
) + 1 AS Rank
FROM v_sales AS u
GROUP BY u.m_id;

但是结果不是预期的:

# m_name   total   Rank
川島智弘    2620    1
河田英毅    0       1
山田忠明    15420   1
永峰弘万    500     1
永山智広    380     1

我需要以下输出:

# m_name    total   Rank 
川島智弘     2620    2
河田英毅     0       5
山田忠明     15420   1
永峰弘万     500     3
永山智広     380     4

有人知道我做错了什么吗?如果有人可以解释为什么我的查询不起作用,那也会很有帮助。 这是一个Fiddle

谢谢

您可以在 MariaDB 10.4 中使用 RANK 功能。

SELECT m_name, SUM(num * price) AS total,
 RANK() OVER(ORDER BY SUM(num * price) DESC)
FROM v_sales
GROUP BY m_id;

Fiddle

无window功能:

SELECT t1.m_name,MAX(t1.total),COUNT(t2.m_name)+1 as RANK
FROM
(SELECT m_name, SUM(num * price) AS total FROM
v_sales
GROUP BY m_id) t1
LEFT JOIN
(SELECT m_name, SUM(num * price) AS total FROM
v_sales
GROUP BY m_id) t2
ON t1.total<t2.total
GROUP BY t1.m_name
ORDER BY 3

Fiddle