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

6ljaweal  于 2023-03-13  发布在  SQLite
关注(0)|答案(1)|浏览(194)

bounty将在7天后过期。回答此问题可获得+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),
    max(city) keep (dense_rank first order by population desc)   --<<--
from
    cities
group by
    country
having
    count(*) > 1

如上所示,即使城市名称不在GROUP BY中,以下列也可以引入城市名称:

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

使用SQL有很多方法可以实现这类操作,我正在SQLite中寻找一种解决方案,它可以让我在计算列中完成这一操作--所有操作都在单个SELECT查询中完成(没有子查询、连接、WITH等)。
问:SQLite中是否有与Oracle的MAX(...) KEEP (DENSE_RANK FIRST/LAST ORDER BY ...)等效的功能?
相关:

olqngx59

olqngx591#

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

相关问题