Oracle SQL 中有一种技术可用于简化聚合查询。
场景:我们在一个特定的列上进行了聚合——但我们实际上想知道来自不同列的信息。
有很多方法可以使用 SQL 来实现。我正在寻找一种解决方案,让我可以在计算列中执行此操作——全部在单个 SELECT 查询中(没有子查询、连接、WITH 等)。
像这样:
--Oracle
--For a given 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 Server 中是否有等效的功能?
相关:
编辑:
我把
MAX()
改成了ANY_VALUE()
,因为我觉得ANY_VALUE()
更容易阅读。
可以通过将
, city desc
添加到 order by
来打破关系,使其具有确定性:
any_value(city) keep (dense_rank first order by population desc, city desc)
SQL Server 没有实现这个。
我正在寻找一种可以让我在计算列中进行操作的解决方案 -- 全部在单个 SELECT 查询中(没有子查询、连接、WITH 等)
有可能但不漂亮(DB Fiddle)。
假设人口是一个正整数,那么您可以使用以下内容(有关此方法背后的想法,请参阅基于串联的解决方案)
select
country,
count(*),
max(population),
SUBSTRING(MAX(FORMAT(population, 'D10') + city), 11, 8000)
from
cities
group by
country
having
count(*) > 1