gpt4 book ai didi

MySQL 5.6 - 类似 DENSE_RANK 的功能,没有 Order By

转载 作者:可可西里 更新时间:2023-11-01 07:49:27 28 4
gpt4 key购买 nike

我有一个这样的表:

+------+-----------+
|caseID|groupVarian|
+------+-----------+
|1 |A,B,C,D,E |
+------+-----------+
|2 |A,B,N,O,P |
+------+-----------+
|3 |A,B,N,O,P |
+------+-----------+
|4 |A,B,C,D,F |
+------+-----------+
|5 |A,B,C,D,E |
+------+-----------+

我想获得一个新列 nameVarian,这样相同的 groupVarian 值具有由 nameVarian 表示的相同排名(例如:v1, v2 等等)。但是,分配给特定 groupVariannameVarian 值应该按照 caseID 的顺序(按照它们在表中出现的顺序)。

输出应该是这样的:

+------+-----------+----------+
|caseID|groupVarian|namevarian
+------+-----------+----------+
|1 |A,B,C,D,E |v1 |
+------+-----------+----------+
|2 |A,B,N,O,P |v2 |
+------+-----------+----------+
|3 |A,B,N,O,P |v2 |
+------+-----------+----------+
|4 |A,B,C,D,F |v3 |
+------+-----------+----------+
|5 |A,B,C,D,E |v1 |
+------+-----------+----------+

最佳答案

对于 MySQL 版本 < 8.0 ( OP's version is 5.6 ):

问题陈述看起来需要 DENSE_RANK groupVarian 的功能;然而事实并非如此。 As explained by @Gordon Linoff :

You appear to want them enumerated by the order they appear in the data.

假设您的表名称是 t(请根据您的代码相应地更改表和字段名称)。这是一个 approach utilizing session variables (对于旧版本的 MySQL),给出所需的结果 ( DB Fiddle ):

SET @row_number = 0;
SELECT t3.caseID,
t3.groupVarian,
CONCAT('v', t2.num) AS nameVarian
FROM
(
SELECT
(@row_number:=@row_number + 1) AS num,
t1.groupVarian
FROM
(
SELECT DISTINCT groupVarian
FROM t
ORDER BY caseID ASC
) AS t1
) AS t2
INNER JOIN t AS t3
ON t3.groupVarian = t2.groupVarian
ORDER BY t3.caseID ASC

另外:我之前尝试模拟 DENSE_RANK 功能,效果很好。尽管也可以稍微调整之前的查询以实现 DENSE_RANK 功能。但是,以下查询效率更高,因为它创建了较少的派生表,并且避免了groupVarian 上的JOIN:

SET @row_number = 1;
SET @group_varian = '';

SELECT inner_nest.caseID,
inner_nest.groupVarian,
CONCAT('v', inner_nest.num) as nameVarian
FROM (
SELECT
caseID,
@row_number:=CASE
WHEN @group_varian = groupVarian THEN @row_number
ELSE @row_number + 1
END AS num,
@group_varian:=groupVarian as groupVarian
FROM
t
ORDER BY groupVarian
) AS inner_nest
ORDER BY inner_nest.caseID ASC

关于MySQL 5.6 - 类似 DENSE_RANK 的功能,没有 Order By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52352877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com