SQLite 相当于 Oracle 的 ANY_VALUE(...) KEEP (DENSE_RANK FIRST/LAST ORDER BY ...)

问题描述 投票:0回答:1

Oracle SQL中有一项技术可以用来简化聚合查询:

在特定列上聚合,但从不同的列获取信息,使用 SELECT 列表中的简单计算列。

--Oracle
--For each country, what city has the highest population? (where the country has more than one city)
--Include the city name as a column.
select
    country,
    count(*),
    max(population),
    any_value(city) keep (dense_rank first order by population desc)   --<<--
from
    cities
group by
    country
having
    count(*) > 1

db<>小提琴

如上图,下面的列可以带入城市名,即使城市名不在GROUP BY中:

 any_value(city) keep (dense_rank first order by population desc)

有很多方法可以使用 SQL 实现这种事情。我正在寻找 SQLite 中的解决方案,让我可以在计算列中执行此操作——全部在单个 SELECT 查询中(没有子查询、连接、WITH 等)。

问题:在 SQLite 中是否有与 Oracle

ANY_VALUE(...) KEEP (DENSE_RANK FIRST/LAST ORDER BY ...)
等效的功能?


相关:


编辑:

我把

MAX()
改成了
ANY_VALUE()
,因为我觉得
ANY_VALUE()
更容易阅读。

可以通过将

, city desc
添加到
order by
来打破关系,使其具有确定性:

any_value(city) keep (dense_rank first order by population desc, city desc)
sql sqlite group-by greatest-n-per-group
1个回答
2
投票
如果使用

MAX()MIN()

 之一,
SQLite 支持聚合查询中的
裸列

例如,您的 Oracle 查询可以简单地写成:

select
    country,
    count(*),
    max(population),
    city -- this is valid and returns the city with the max population
from
    cities
group by
    country
having
    count(*) > 1

查看演示

© www.soinside.com 2019 - 2024. All rights reserved.