2014-12-04 58 views
0

的我有列名的表,QueuePositionSQL - 如何重新安排一組行

Name QueuePosition 
John  1 
Paul  1 
Mike  2 
Sarah  3 
Kevin  4 
George 4 

我如何重新安排他們儘快要這樣?

Name QueuePosition 
John  1 
Paul  2 
Mike  3 
Sarah  4 
Kevin  5 
George 6 

感謝

編輯-Should已經比較具體

我需要如果可能的話它是永久性的。不只是一個選擇語句。

列表中不會超過10個名字。可能必須將它們保存在數組中並覆蓋整個列表。我想知道有沒有這樣做的快速方法。

+0

我不知道你問 - 你可以發佈你試過的代碼? – 2014-12-04 13:04:05

+0

如果我理解的很好,可以將所有這些名稱插入到一個新表中,並將QueuePosition定義爲AUTOINCREMENT。 – 2014-12-04 13:05:57

+0

您正在使用哪些DBMS? Postgres的?甲骨文? – 2014-12-04 13:09:41

回答

1

首先,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); 
+0

對不起剛纔編輯我的帖子。 – user237462 2014-12-04 13:21:43

+0

謝謝你,先生。 – user237462 2014-12-04 15:43:20

+0

SQLite沒有窗口函數。 – 2014-12-04 19:36:48

1

嘗試

update yourTableName set QueuePosition = ROWID 
+0

先前刪除的行可能會導致序列中出現空白。 – 2014-12-04 19:39:19