Sql server 分组行上的排序依据和顶部
我如何按日期订购描述我的分组项目并获得前20名 例如:Orderproduct表有OrderID、ProductId、Date、Price,我想按ProductId分组,并按Date desc对每个分组进行排序,然后得到top 20和avgprice 在LINQ上,就是这样,但是生成的sql非常脏,性能非常差 OrderProduct .GroupBy(g => g.ProductId) .Select(s => new{ s.Key, Values = s.OrderByDescending(o => o.Date).Take(20) }) .Select(s => new{ Avg = s.Values.Average(a => a.Price) } )Sql server 分组行上的排序依据和顶部,sql-server,tsql,sql-server-2008,Sql Server,Tsql,Sql Server 2008,我如何按日期订购描述我的分组项目并获得前20名 例如:Orderproduct表有OrderID、ProductId、Date、Price,我想按ProductId分组,并按Date desc对每个分组进行排序,然后得到top 20和avgprice 在LINQ上,就是这样,但是生成的sql非常脏,性能非常差 OrderProduct .GroupBy(g => g.ProductId) .Select(s => new{ s.Key, Values = s.OrderByDes
根据您的意见,这可能有效:
SELECT [Date],
ProductID,
MIN(Price) as Min,
MAX(Price) as MAX,
AVG(Price) as Avg
FROM OrderProduct o1
WHERE [Date] IN (SELECT TOP 20 [Date]
FROM OrderProduct o2
WHERE o1.productid = o2.productid)
GROUP BY [Date], ProductID
ORDER BY [Date] DESC
如果我理解你的问题,这可能对你有用
select ProductId,
avg(price) as AvgPrice
from ( select ProductId,
Price,
row_number() over(partition by ProductId order by [Date] desc) as rn
from Orderproduct
) as O
where rn <= 20
group by ProductId
这是否得到了所有行所需的值?我知道你只想要每个产品的前20名。如果这不正确,我只是不想把时间花在前20名上。前20名是否意味着20个最高价格,或20个最近日期,或20个最近日期?每个productID每天是否有一个以上的价格
SELECT [ProductID], [Date], [Price]
FROM [OrderProduct]
ORDER BY [ProductID] asc, [Date] desc, [Price] desc
COMPUTE AVG(Price) BY [ProductID];
如果您按ProductID分组,那么您希望在其他字段上进行什么聚合?我需要前20名排序价格中的最小值、最大值、平均值,因此您希望聚合价格,但是日期和订单ID呢?排除这些吗?你需要对它们做些什么。OrderId我将忽略,date我将使用,只是为了排序如果你想按它排序,你需要在结果集中使用date…不,我想筛选分组结果,你正在分组所有结果,我只需要按排序的前20名进行分组date@Alexandre-那么,你可能应该明确你想要什么,因为目前还不清楚。例如productId 19有200个寄存器,我只想知道按日期排序的前20个结果的maxprice每个productId的日期范围会不同吗?不,只是最近的前20个