繁体   English   中英

根据条件添加列并用升序数填充

[英]add column and fill with ascending numbers based on condition

给定这张表

id      secId
 1          2
 2          2
 3          2
 4          1
 5          3
 6          3

我想添加一个新列“ sortIndex”,并将其值初始化为每组相等的secId的递增int值。 所以结果表是

id      secId       sortIndex
 1          2               1
 2          2               2
 3          2               3
 4          1               1
 5          3               1
 6          3               2

因此,对于每组相等的secId,我都有一个新的序列“ 1,2,3,4,...”。如果有可能,单个查询就很棒。

您正在尝试在MySQL中模拟row_number。 您需要使用变量。

SET @row_number:=0;
SET @sec_id:='';
SELECT id, @row_number:=CASE WHEN @secid=secid THEN @row_number+1 ELSE 1 END AS row_number, 
@secid:=secid AS secid
FROM your_table
ORDER BY secid;

您可以在以下位置找到更多详细信息

http://blog.sqlauthority.com/2014/03/09/mysql-reset-row-number-for-each-group-partition-by-row-number/

给出一个行号。

检查secId ,如果同一单位中的@curRow1

询问

select Id,secId,( 
  case secId 
  when @curA
  then @curRow := @curRow + 1 
  else @curRow := 1 and @curA := secId end
) as sort_index
from your_table_name t,
(select @curRow := 0, @curA := '') r
order by Id,secId;

SQL小提琴演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM