简体   繁体   中英

Sql Query using group clause

this is my table snapshot of sql server.

在此输入图像描述

i want to write a sql query , which will return only 3 row, whcih contain max offer from 3 diffrent category. like in my result there should be 3 different category id, and correspondence to that category's Offer that offer should be maximum in that category

this is my desired output 在此输入图像描述

as you can see there is 3 diffrent category , and offer belongs to that category is maximum from that category

see

If you just want the Category and the maximum value:

SELECT TOP 3 Cat_Id, MAX(Offer) FROM Products GROUP BY Cat_Id

But if you want also other fields, you have to use a rank function :

SELECT TOP 3 * FROM
    (SELECT ROW_NUMBER() OVER(PARTITION BY Cat_Id ORDER BY Offer DESC) AS RowNumber,
        Cat_Id, Offer, Name, Model
     FROM Products) AS T
WHERE RowNumber=1

There 2 different approach to your query:

select * from (
select *, dense_rank() over( order by ct desc) t from (
select *, max(Offer) over (partition by cat_id) ct from Products
) o)o2 where t<3

or

select * from Products s inner join (
select top 3 Cat_id, max(Offer) max_offer from Products
group by Cat_id
order by max_offer desc) o on o.Cat_id=s.Cat_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM