这是我的table
sql server快照。
我想写一个sql
query
,它只返回3行,包含3个不同类别的最大报价。
在我的结果中应该有3个不同的类别ID,并且与该类别的提议的对应关系应该是该类别中的最大值
这是我想要的输出
正如您所看到的那样,有3个不同的类别,并且该类别的商品属于该类别的最大类别
见
答案 0 :(得分:2)
如果您只想要类别和最大值:
SELECT TOP 3 Cat_Id, MAX(Offer) FROM Products GROUP BY Cat_Id
但如果您还想要其他字段,则必须使用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
答案 1 :(得分:0)
您的查询有两种不同的方法:
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
或
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