我提取分组最大值(data
CTE模拟实际表中的一组连接):
with data as (
select 'Austria' as country, 1 as id, 'red' as colour, 120 as quantity
union all select 'Austria', 2, 'green', 96
union all select 'Austria', 3, 'blue', 103
union all select 'Belgium', 1, 'red', 33
union all select 'Belgium', 2, 'green', 12
union all select 'Belgium', 3, 'blue', 40
)
select country, colour, quantity
from (
select country, colour, quantity,
rank() over (partition by country order by quantity desc, id) as position
from data
group by country, id, colour, quantity
) subquery
where position=1;
这样可以正常,但是我强迫在子查询中使用RANK()
调用来包装查询,因为此替代方法会触发语法错误:
-- [...]
select country, colour, quantity,
rank() over (partition by country order by quantity desc, id) as position
from data
group by country, id, colour, quantity
having rank() over (partition by country order by quantity desc, id)=1;
窗口函数只能出现在SELECT或ORDER BY子句中。
是否有替代语法来避免此限制或子查询是唯一合理的方法?
最终目标是将此代码集成到一组更大的动态生成的SQL表达式中。如果我可以保留单个查询,我可以用数组定义不同的部分(选择,连接表,在哪里,分组,拥有和排序)。否则我需要考虑重大改写。
答案 0 :(得分:9)
你可以使用排名第一的领带,如下所示
select top (1) with ties country, colour, quantity,
rank() over (partition by country order by quantity desc, id) as position
from data
--group by country, id, colour, quantity
order by rank() over (partition by country order by quantity desc, id)
答案 1 :(得分:3)