我有一个返回一行的查询。有什么办法可以在表格排序时找到我要查询的行的行索引吗?
我已经尝试rowid
,但在我期待第7行的时候得到#582。
例如:
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
我尝试了意外结果的rowid:
SELECT rowid FROM Categories WHERE CategoryID = 'C_L7761O2U ORDER BY Name
编辑:我也尝试过J Cooper的建议(如下),但行数不正确。
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());
答案 0 :(得分:17)
以下是在 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;
答案 1 :(得分:0)
这是一个有趣的技巧,您可以在Spatialite中使用它来获取值的顺序。如果使用count()函数,并且WHERE子句仅限制值&gt; =当前值,则计数实际上将给出顺序。因此,如果我有一个名为“mypoints”的点层,其中包含“value”和“val_order”列,那么:
SELECT value, (
SELECT count(*) FROM mypoints AS my
WHERE my.value>=mypoints.value) AS val_order
FROM mypoints
ORDER BY value DESC;
给出值的降序。 我可以这样更新“val_order”列:
UPDATE mypoints SET val_order = (
SELECT count(*) FROM mypoints AS my
WHERE my.value>=mypoints.value
);
答案 2 :(得分:-3)
您要问的内容可以用两种不同的方式解释,但我假设您要对结果表进行排序,然后根据排序对这些行进行编号。
declare @resultrow int
select
@resultrow = row_number() OVER (ORDER BY Name Asc) as 'Row Number'
from Categories WHERE CategoryID = 'C_L776102U'
select @resultrow