我很难搞清楚并尝试解决这个问题。 您能否帮助我提供一个逻辑或想法如何根据销售情况获得每个分支的每个类别的排名?
例如:
与其他分支相同。我只需要每个branch_code_id
的类别等级。
我无法弄清楚如何循环这个。排名将放在“r”列中,您可以在Excel输出中看到。
顺便说一句,这是我用来获取你在屏幕截图中看到的结果的sql语句。
SELECT
a.id,
a.date,
a.branch_code_id,
SUM(b.amount),
c.category
FROM
sales_add_h AS a
INNER JOIN sales_add_i AS b ON a.id = b.sales_h_id
INNER JOIN control_panel_item_create AS c ON b.item_code_id = c.id
GROUP BY c.category, a.branch_code_id, b.amount
ORDER BY SUM(b.amount) DESC
谢谢大家!
答案 0 :(得分:4)
尝试此查询
SELECT
@rn:=if(@prv=branch_code_id, @rn+1, 1) as rId,
@prv:= branch_code_id as branch_code_id,
val,
id,
date,
category
FROM
(SELECT
a.id,
a.date,
a.branch_code_id,
SUM(b.amount) as val,
c.category
FROM
sales_add_h AS a
INNER JOIN
sales_add_i AS b ON a.id = b.sales_h_id
INNER JOIN
control_panel_item_create AS c ON b.item_code_id = c.id
GROUP BY
c.category, a.branch_code_id, b.amount
ORDER BY
a.branch_code_id, SUM(b.amount) DESC)tmp
JOIN
(SELECT @rn:=0, @prv:=0)t
SQLFIDDLE 了解排名如何运作。
如上所述,我已经为每个branch_id做了排名,如果你想为特定分支中的每个类别排名,而不是需要添加另一个存储类别的变量并在if clause
内进行比较需要相应地对内部查询中的数据进行排序order by c.category, a.branch_code_id, SUM(b.amount) DESC