這裏,這給出一個嘗試:
select name, city, serial_number from
(select name, city
, (case when @city <> city then @citynum := 1 else @citynum := @citynum + 1 end) as serial_number
, (case when @city <> city then @city := city end) as v
from tbl_cities, (select @citynum := 0, @city := '') as c
order by city) as cities
這裏是你投放了鏈接:http://sqlfiddle.com/#!2/615f5/1。
您需要將'tbl_cities'更改爲表格的名稱。
我無法將它保存爲視圖或在更新語句中使用,因爲它使用變量。一種快捷的方法是使用上面的select語句創建一個新表,並在添加新數據時定期運行。
drop table if exists tbl_cities_serial;
create table tbl_cities_serial(select name, city, serial_number from
(select name, city
, (case when @city <> city then @citynum := 1 else @citynum := @citynum + 1 end) as serial_number
, (case when @city <> city then @city := city else @city end) as v
from tbl_cities, (select @citynum := 0, @city := '') as c
order by city) as cities)
來源
2013-10-12 22:00:02
Ben
你到目前爲止嘗試了什麼? –
我嘗試生成序列號但無法重複輸入 – user2021672
當您選擇數據時,在模擬MySQL中的RANK()OVER PARTITION時可能會出現這種情況,但您需要使用用戶變量,但如果表包含很多記錄 –