1. 程式人生 > 其它 >mysql根據某些列分組,然後每組生成從1遞增的序號

mysql根據某些列分組,然後每組生成從1遞增的序號

技術標籤:資料庫

場景舉例,方便理解

test2 表

表格要求用 operate、tid 列分組,並且查詢結果生成如下px列序號:

result:

查詢語句:

select a.*,
(select count(*) as 序號 from test2 as b where
a.tid=b.tid and a.operat = b.operat 
and a.id >=b.id ) as px
from test2 as a  ORDER BY operat ,tid;


根據a.tid=b.tid and a.operat = b.operat條件進行分組
根據a.id >=b.id進行序號生成