这是一道常见的面试题,在实际项目中经常会用到。
需求:求出以产品类别为分组,各个分组里价格最高的产品信息。
实现过程如下:
declare @t table(
ProductID int,
ProductName varchar(20),
ProductType varchar(20),
Price int)
--测试数据
insert @t
select 1,'name1','P1',3 union all
select 2,'name2','P1',5 union all
select 3,'name3','P2',4 union all
select 4,'name4','P2',4
--做法一:找到每个组里,价格最大的值;然后再找出每个组里价格等于这个值的
--缺点:要进行一次join
select t1.*
from @t t1
join (select ProductType,
max(Price) Price
from @t
group by ProductType) t2 on t1.ProductType = t2.ProductType
where t1.Price = t2.Price
order by ProductType
--做法二:利用over(),将统计信息计算出来,然后直接筛选结果集。
--over() 可以让函数(包括聚合函数)与行一起输出。
;with cte as(
select *, max(Price) over(partition by (ProductType)) MaxPrice
from @t)
select ProductID,ProductName,ProductType,Price from cte where Price = MaxPrice
order by ProductType
--over() 的语法为:over([patition by ] <order by >)。需要注意的是,over() 前面是一个函数,如果是聚合函数,那么order by 不能一起使用。
--over() 的另一常用情景是与 row_number() 一起用于分页。