Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

sql - Getting row number for query

I have a query which will return one row. Is there any way I can find the row index of the row I'm querying when the table is sorted?

I've tried rowid but got #582 when I was expecting row #7.

Eg:

    CategoryID  Name            
    I9GDS720K4  CatA
    LPQTOR25XR  CatB
    EOQ215FT5_  CatC
    K2OCS31WTM  CatD
    JV5FIYY4XC  CatE
--> C_L7761O2U  CatF <-- I want this row (#5)
    OU3XC6T19K  CatG
    L9YKCYAYMG  CatH
    XKWMQ7HREG  CatI

I've tried rowid with unexpected results:

SELECT rowid FROM Categories WHERE CategoryID = 'C_L7761O2U ORDER BY Name

EDIT: I've also tried J Cooper's suggestion (below), but the row numbers just aren't right.

 using (var cmd = conn.CreateCommand()) {
        cmd.CommandText = string.Format(@"SELECT (SELECT COUNT(*) FROM Recipes AS t2             WHERE t2.RecipeID <= t1.RecipeID) AS row_Num 
                FROM Recipes AS t1 
                WHERE RecipeID = 'FB3XSAXRWD'
                ORDER BY Name";
        cmd.Parameters.AddWithValue("@recipeId", id);
        idx = Convert.ToInt32(cmd.ExecuteScalar());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...