我想获得每个月最畅销的商品/产品。我尝试使用GROUP BY函数,但是我的问题是如何每个月只获得一种产品。
O(NlogN)
此外,如何在mysql中使用SELECT MONTHNAME(date), product, SUM(quantity)
FROM mytable
GROUP BY MONTHNAME(date), product
函数?我想通过使用我每月只能得到一种产品?
这就是我想要得到的:
答案 0 :(得分:0)
SELECT
month, n, product, quantity
FROM
( SELECT @prev := '', @n := 0 ) init
JOIN
( SELECT @n := if(MONTHNAME(date) != @prev, 1, @n + 1) AS n,
@prev := MONTHNAME(date),
MONTHNAME(date) AS month, product, SUM(quantity) AS quantity
FROM mytable
GROUP BY
MONTHNAME(date), product
ORDER BY
MONTHNAME(date) ASC,
SUM(quantity) DESC
) x
WHERE n <= 1
ORDER BY month, n