kdb/Q How to renumber rows in table?

51 Views Asked by At

If I have a table like the one below:

Iteration Score
1 20
2 87
3 10

I reordered by Score descending:

ordered: `Score desc first_table;

Iteration Score
2 87
1 20
3 10

How can I then renumber the Iteration column, so the output is something like below? I am thinking of creating a new column that gets the index # of every row, then replacing the original Iteration column.

Iteration Score
1 87
2 20
3 10
2

There are 2 best solutions below

1
rianoc On BEST ANSWER

You can sort the columns not the table:

update asc Iteration, desc Score from tab
0
terrylynch On

Given that your table in practice likely has many more columns, you could also regenerate the index column after an xdesc

q)update iteration:i+1 from `score xdesc([]iteration:1+til 3;score:20 87 10;col1:3?`3;col2:3?10.0)
iteration score col1 col2
-----------------------------
1         87    enf  5.347096
2         20    fgl  7.85033
3         10    plh  7.111716