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
如上图,下面的列可以带入城市名,即使城市名不在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)