【发布时间】:2017-11-02 19:11:00
【问题描述】:
我正在获取分组最大值(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 表达式集中。如果我可以保留一个查询,我可以用数组定义不同的部分(选择、连接表、位置、分组依据、拥有和排序依据)。否则我需要考虑进行重大改写。
【问题讨论】:
标签: sql sql-server sql-server-2008-r2