【问题标题】:User-defined variable in ranking statement排名语句中的用户定义变量
【发布时间】:2021-03-27 13:34:27
【问题描述】:

我会在此问题上提供任何帮助。我已经花了几个小时没有任何真正的解决方案。 我有一个 SQL

SELECT to_place, rank
FROM
  (SELECT g1.to_place as to_place, g1.pcount as pcount, 
                @rank := IF(@current_to_place = g1.to_place, @rank + 1, 1) AS rank,
                @current_to_place := g1.to_place 
  FROM 
          (select 
          to_place, count(*) as pcount
          from temp_workflows
          group by to_place
          order by to_place,pcount desc) g1
  ORDER BY g1.to_place, g1.pcount DESC) ranked

在表 g1 中,我对数据进行分组以查找最常见的 to_place。然后我想按升序排列这些出现(这样我以后可以选择每个 to_place 类别中最常见的前 3 个。

问题是用户定义的变量是不可预测的(@rank 有时总是 1),这可能与在一个语句中我不应该引用同一个变量(current_to_place)这一事实有关。我读了很多关于使用单独的语句等的内容,但我可以找到一种方法来以不同的方式编写我的语句。如何在其他地方定义 @current_to_place 以使结果相同? 提前感谢您的帮助。

【问题讨论】:

  • 样本数据会很好,同时请注意等级在版本 8 中成为保留字

标签: mysql variables select user-defined


【解决方案1】:

我认为你应该测试 pcount 以获得排名并且你应该初始化变量

DROP TABLE IF EXISTS T;
CREATE TABLE T
(to_place int);

insert into t values (1),(2),(2),(3),(3),(3);
SELECT to_place, rank
FROM
  (
  SELECT g1.to_place as to_place, g1.pcount as pcount, 
                @rank := IF(@current_to_place <> pcount, @rank + 1, 1) AS rank,
                @current_to_place := pcount 
  FROM 
          (select 
          to_place, count(*) as pcount
          from t
          group by to_place
          order by to_place,pcount desc) g1
 cross join(select @rank:=0,@current_to_place:=0) r
  ORDER BY g1.pcount DESC
  )
   ranked

+----------+------+
| to_place | rank |
+----------+------+
|        3 |    1 |
|        2 |    2 |
|        1 |    3 |
+----------+------+
3 rows in set (0.016 sec)

【讨论】:

  • 很好,初始化变量是解决问题的方法,尽管我不确定我是否理解逻辑,因为我认为变量是在第一次使用变量时初始化的。但无论如何,谢谢你的帮助。
猜你喜欢
  • 2021-08-11
  • 2017-07-29
  • 1970-01-01
  • 2023-03-19
  • 2017-03-21
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
相关资源
最近更新 更多