如何将条件与 RANK 语句一起使用

How to use conditions with a RANK statement

以下代码完成了它的工作:它为我提供了每个类别的前 10 个结果。

SELECT *
FROM (
SELECT *, RANK() OVER (PARTITION BY "pera_id" ORDER BY "surface" DESC) AS rnk
FROM "testBadaBing"
) AS x
WHERE rnk <= 10

现在我想添加条件,以便结果的数量可以根据条件而变化。示例:如果“note”= 1,那么我想保留 1 个结果,否则将其设为 3。

我尝试了一些您可以在下面使用 CASE WHEN 语句看到的内容,但正如您所料,它不起作用。返回错误:

1 - near "CASE": syntax error

SELECT *
CASE WHEN "note" = 1 THEN
SELECT *
    FROM (
        SELECT *, RANK() OVER (PARTITION BY "pera_id" ORDER BY "surface" DESC) AS rnk
        FROM "testBadaBing"
    ) AS x
WHERE rnk <= 1
ELSE
SELECT *
    FROM (
        SELECT *, RANK() OVER (PARTITION BY "pera_id" ORDER BY "surface" DESC) AS rnk
        FROM "testBadaBing"
    ) AS x
WHERE rnk <= 3
END

您有什么想法可以让这项工作发挥作用吗?我对 SQL 的了解非常有限。由于我在 QGIS 环境中工作,代码必须 SQLite/SpatiaLite 兼容。谢谢

您可以在外部查询的 WHERE 子句中使用布尔逻辑:

SELECT *
FROM (
    SELECT t.*, 
        RANK() OVER (PARTITION BY "pera_id" ORDER BY "surface" DESC) AS rnk
    FROM "testBadaBing" t
) AS x
WHERE ("note" = 1 and rnk = 1) OR rnk <= 3