Getting row number for query

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 07:31:10

Here is a way to get the row number in Sqlite:

SELECT CategoryID,
       Name,
       (SELECT COUNT(*)
        FROM mytable AS t2
        WHERE t2.Name <= t1.Name) AS row_Num
FROM mytable AS t1
ORDER BY Name, CategoryID;

Here's a funny trick you can use in Spatialite to get the order of values. If you use the count() function with a WHERE clause limiting to only values >= the current value, then the count will actually give the order. So if I have a point layer called "mypoints" with columns "value" and "val_order" then:

SELECT value, (
SELECT count(*) FROM mypoints AS my 
WHERE my.value>=mypoints.value) AS val_order
FROM mypoints 
ORDER BY value DESC;

Gives the descending order of the values. I can update the "val_order" column this way:

UPDATE mypoints SET val_order = (
SELECT count(*) FROM mypoints AS my 
WHERE my.value>=mypoints.value
);

What you are asking can be explained in two different ways, but I'm assuming you want to sort the resulting table and then number those rows according to the sort.

declare @resultrow int

select 
      @resultrow = row_number() OVER (ORDER BY Name Asc) as 'Row Number'
from Categories WHERE CategoryID = 'C_L776102U'

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