Reputation: 5962
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
Upvotes: 0
Views: 58
Reputation: 3084
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
Upvotes: 0
Reputation: 18443
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
Upvotes: 2