H2数据库 - Rank()和Row_Num()的替代

时间:2012-01-16 12:26:14

标签: sql h2

我在我的java应用程序中使用H2数据库。它似乎不支持rank()row_num()函数,因为它们仍在roadmap list

这是我正在尝试执行的查询

select * from (
   select *,
          rank() over(partition by MSISDN order by PORT_IN_DATE desc) rank 
   from TEST_PORTIN
) s 
where rank = 1 
  AND PORT_IN_DATE > '2012-01-16 23:20:27' 
ORDER BY PORT_IN_DATE

1 个答案:

答案 0 :(得分:1)

您的特定查询不需要RANK()。您可以按如下方式重写它:

SELECT *
FROM TEST_PORTIN t1
WHERE PORT_IN_DATE > '2012-01-16 23:20:27'
AND NOT EXISTS (
    SELECT *
    FROM TEST_PORTIN t2
    WHERE t1.MSISDN = t2.MSISDN -- PARTITION BY clause translation
    AND t1.PORT_IN_DATE > t2.PORT_IN_DATE -- ORDER BY clause translation
)
ORDER BY PORT_IN_DATE

或者,使用量化的比较谓词

有点发烧友(但不一定更快)
SELECT *
FROM TEST_PORTIN t1
WHERE PORT_IN_DATE > '2012-01-16 23:20:27'
AND PORT_IN_DATE >= ALL (
    SELECT PORT_IN_DATE
    FROM TEST_PORTIN t2
    WHERE t1.MSISDN = t2.MSISDN
)
ORDER BY PORT_IN_DATE