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