SQLite - Update column of the same table, based on result from row_number()

Cheok Yan Cheng :

After several tries, I was able to generate a row_number() column with the value I wished.

select "order", row_number() over win - 1, type, title, body, searched_string from plain_note 

WINDOW win AS (
    order by 
        title desc,
        case when type = 0 then body else searched_string end desc
)

enter image description here

Now, I would like to overwrite entire "order" column, with the value from "row_number() over win - 1"

For instance,

  • In the 1st row, I would like to update "order" column (original value 13) with value 0.
  • In the 2nd row, I would like to update "order" column (original value 14) with value 1.
  • ... and so on.

May I know, what is the correct SQLite statement to do so? Thanks.


The approach I had tried so far is

update plain_note set "order" = (
    select row_number() over win - 1 from plain_note 

    WINDOW win AS (
        order by 
            title desc,
            case when type = 0 then body else searched_string end desc
    )
);

However, this will make ALL rows of "order", having the 1st row of "row_number() over win - 1" value, which is 0.

forpas :

Your code is missing a link between the table's rows and the subquery's rows.
I would write the update method like this:

with cte as (
  select *, row_number() over win - 1 as rn from plain_note

  window win as (order by 
    title desc,
    case when type = 0 then body else searched_string end desc
  )    
)
update plain_note set "order" = (select rn from cte where "order" = plain_note."order");

This will work of the values in the column "order" are unique.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=376412&siteId=1