Sqlite Increment column value based on previous row's value

谁说我不能喝 提交于 2021-02-08 09:51:23

问题


How do I increment a column value based on previous column value in Sqlite? I need to do this for 1000+ rows. I have data in the first row say 100. I need to increment the next 1000 rows by 2.

Row#  ColName
1       100
2       102
3       104
4       106

I tried something like this: Update Table SET ColName = (Select max(ColName ) from Table ) + 2 but this puts 102 in all columns.


回答1:


Assuming that this table has a rowid column, it is possible to count how many previous rows there are:

UPDATE MyTable
SET ColName = (SELECT MAX(ColName)
               FROM MyTable
              ) +
              (SELECT COUNT(*)
               FROM MyTable AS Previous
               WHERE Previous.rowid < MyTable.rowid
              ) * 2
WHERE ColName IS NULL


来源:https://stackoverflow.com/questions/23834181/sqlite-increment-column-value-based-on-previous-rows-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!