SQLite等效于Oracle的ANY_VALUE(...)KEEP(DENSE_RANK第一个/最后一个排序依据...)

nhaq1z21  于 2023-03-19  发布在  SQLite
关注(0)|答案(1)|浏览(157)

bounty将在22小时后过期。回答此问题可获得+50声望奖励。User1974希望引起更多人关注此问题。

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<>fiddle
如上所示,即使城市名称不在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)
nvbavucw

nvbavucw1#

如果使用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

请参见demo

相关问题