首先,SQL表格表示無序集合。所以,除非你有另一個專欄,否則沒有辦法確保「John」出現在「Paul」之前。
您想要的規範方法是row_number()
函數。這是大多數數據庫支持的ANSI標準功能。該查詢是:
select name, row_number() over (order by QueuePosition) as QueuePosition
from table t;
這也可以被摺疊成update
,但語法將由數據庫而有所不同。
編輯:
SQLite中,你可以這樣做:
with toupdate as (
select name, row_number() over (order by QueuePosition) as QueuePosition
from tablename
)
update tablename
set QueuePosition = (select QueuePosition from toupdate where toupdate.name = tablename.name);
編輯II;
SQLite中,你可以這樣做:
with toupdate as (
select name, (select count(*) from tablename t2 where t2.QueuePosition <= t.QueuePosition) as QueuePosition
from tablename t
)
update tablename
set QueuePosition = (select QueuePosition from toupdate where toupdate.name = tablename.name);
我不知道你問 - 你可以發佈你試過的代碼? – 2014-12-04 13:04:05
如果我理解的很好,可以將所有這些名稱插入到一個新表中,並將QueuePosition定義爲AUTOINCREMENT。 – 2014-12-04 13:05:57
您正在使用哪些DBMS? Postgres的?甲骨文? – 2014-12-04 13:09:41