我有桌子:订单和产品。 如何在MySQL 5.6中生成排名?
如果产品价值相同,则排名也必须相同。 下面我需要按计数排名
SELECT
count(productpk), productpk,
@prev := @curr,
@curr := count(productpk),
@rank := IF(@prev = @curr, @rank, @rank+1) AS rank
FROM orders AS om
JOIN products AS p ON om.PK=p.p_order,
(SELECT @curr := null, @prev := null, @rank := 0) sel1
GROUP BY productpk ORDER BY count(productpk);
有效结果是(count - > rank):
答案 0 :(得分:1)
此查询应该可以解决问题。
SELECT
sq.productpk,
sq.cp,
@rank := IF(@prev = sq.cp, @rank, @rank + 1) AS rank,
@prev := sq.cp
FROM
(
SELECT
productpk,
COUNT(productpk) AS cp
FROM orders o
JOIN products p ON o.PK = p.p_order
GROUP BY productpk
) sq
, (SELECT @prev := NULL, @rank := 0) var_init_subquery
ORDER BY sq.cp DESC
SELECT
子句中的顺序很重要。当你第一次做这样的事情时
@prev := @curr,
然后是这样的
@rank := IF(@prev = @curr,...
没有意义,因为@prev
总是等于@curr
。顺便说一下,@curr
在这种情况下也毫无意义。
您必须将@prev
与IF()
函数中的当前行进行比较。之后,将当前行分配给@prev
。读取下一行时,@prev
仍保留上一行的值。
最后,您必须将分组查询放在子查询中。人们不会认为这是必要的,因为查询在逻辑上像
一样处理但MySQL并不是这样做的,至少在涉及用户定义的变量时不会这样做。将此简单测试视为证据:
root@localhost:playground > select a, @r:=@r+1 as r from bar, (select @r := 0) sq;
+------+------+
| a | r |
+------+------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 1 | 6 |
| 1 | 7 |
| 1 | 8 |
| 1 | 9 |
| 1 | 10 |
| 2 | 11 |
| 2 | 12 |
| 2 | 13 |
| 2 | 14 |
| 2 | 15 |
+------+------+
15 rows in set (0.00 sec)
root@localhost:playground > select a, @r:=@r+1 as r from bar, (select @r := 0) sq group by a;
+------+------+
| a | r |
+------+------+
| 1 | 1 |
| 2 | 11 |
+------+------+
2 rows in set (0.00 sec)
答案 1 :(得分:0)
您可以使用具有相同结果集的内部联接
来执行此操作 var query = from t in root.Descendants("Action") where (string)t.Attribute("Attribute") == "urn:oasis:names:tc:xacml:1.0:action:action-id" select t;