使用某些where和order by子句查找行和总行的位置

时间:2017-04-04 16:20:43

标签: sql database h2 hsqldb

我有whereorder by子句的SQL查询:

SELECT "id" FROM "persons" 
WHERE "id" in (10,20,30,40,50,60,70,80,90,100) 
ORDER BY "id" DESC

现在我需要获取id = 20的行的位置以及上面查询中找到的行总数。所以我做了

SELECT "id",pos FROM(
   SELECT "id", rownum() as pos FROM(
       SELECT "id" FROM "persons" 
       WHERE "id" in (10,20,30,40,50,60,70,80,90,100)
       ORDER BY "id" DESC
   )
)
WHERE "id"=20;

但是,我的上一次查询只给出了行的位置。我现在怎样才能获得总行数?条件:没有window functions,因为我使用不支持它们的RDBMS - h2和hsqldb。

2 个答案:

答案 0 :(得分:1)

看看这是否有帮助。

 SELECT id,
  (SELECT Count(*) from persons per1 where per1.id< per2.id) AS Rownumber  
 FROM persons per2
 WHERE id in (10,20,30,40,50,60,70,80,90,100) 
 ORDER BY id DESC

答案 1 :(得分:1)

尝试使用HSQLDB

WITH p("id", "pos") AS ( SELECT "id", rownum() AS "pos" FROM "persons" 
   WHERE "id" IN (10,20,30,40,50,60,70,80,90,100)
   ORDER BY "id" DESC) 
SELECT "id", "pos", (select count(*) from P) AS "count" FROM P
WHERE "id"=20;