Sql Server
-
2012년 4월 30일 월요일 오전 5:46
Kindly anyone suggest the following query is the best way to get the top 10 records from each group, in the performance wise.
SELECT * FROM
(
SELECT PrdVarProductType,ROW_NUMBER() OVER (PARTITION BY PrdVarProductType ORDER BY PrdVarProductType,PrdDteCreateDate DESC)AS RowNumber
FROM dbo.KKVIPrdMSt
WHERE PrdChrActiveYN='Y'
)AS T
WHERE RowNumber<=10
ORDER BY PrdVarProductTypeThanks in Advance,
Prathees
모든 응답
-
2012년 4월 30일 월요일 오전 5:51Performance depends on how the Indexes have been defined for the table KKVIPrdMst....We cannot talk about the performance aspect by looking at the query alone.
Murali Krishnan
-
2012년 4월 30일 월요일 오전 5:55답변자
Yep, this is one way, another one would be using CROSS APPLY operator, see example
SELECT S.SupplierID, S.CompanyName, CA.ProductID, CA.UnitPrice
FROM dbo.Suppliers AS S
CROSS APPLY
(SELECT TOP (10) *
FROM dbo.Products AS P
WHERE P.SupplierID = S.SupplierID
ORDER BY UnitPrice DESC, ProductID DESC) AS CA
ORDER BY S.SupplierID, CA.UnitPrice DESC, CA.ProductID DESC;Best Regards, Uri Dimant SQL Server MVP http://dimantdatabasesolutions.blogspot.com/ http://sqlblog.com/blogs/uri_dimant/
-
2012년 4월 30일 월요일 오전 5:56
Thank you Murali Krishnan,
This is the right way to retrieve the top 10 records from each group or give your suggestion.
-
2012년 4월 30일 월요일 오전 6:00
Yes.. That would work. You can use CTE as well.
WITH CTE AS ( SELECT PrdVarProductType,ROW_NUMBER() OVER (PARTITION BY PrdVarProductType ORDER BY PrdVarProductType,PrdDteCreateDate DESC)AS RowNumber FROM dbo.KKVIPrdMSt WHERE PrdChrActiveYN='Y' ) SELECT * FROM CTE WHERE RowNumber <= 10
Murali Krishnan
-
2012년 4월 30일 월요일 오후 6:12중재자
Please check these blogs that explain this problem from performance point of view
Optimizing TOP N per Group Queries - blog by Itzik Ben-Gan explaining various optimization ideas
Including an Aggregated Column's Related Values - Erik and mine blog presenting several solutions of the problem with explanations for each
Including an Aggregated Column's Related Values - Part 2 - my blog post with use cases for the previous blogFor every expert, there is an equal and opposite expert. - Becker's Law
My blog- 답변으로 표시됨 Kalman TothMicrosoft Community Contributor, Moderator 2012년 5월 8일 화요일 오전 12:26

