Saturday, 14 December 2013

Getting Top N Values in SQL Server.

Example 1:

SELECT TOP 5
  SOD.[ModifiedDate]
 ,SUM(SOD.OrderQty) OrderQty
FROM [Sales].[SalesOrderDetail] SOD
GROUP BY SOD.[ModifiedDate]

ORDER BY  2 DESC










Example 2:

SELECT TOP 5
 Convert(Date,SOD.[ModifiedDate])
, PC.[Name]
, PSC.[Name] 
, P.[Name]  
, SUM(SOD.OrderQty) OrderQty
FROM 
[Production].[Product] P
JOIN [Production].[ProductSubcategory] PSC
ON P.ProductSubcategoryID = PSC.ProductSubcategoryID
JOIN [Production].[ProductCategory] PC
ON PC.[ProductCategoryID] = PSC.ProductSubcategoryID
JOIN [Sales].[SalesOrderDetail] SOD
ON SOD.ProductID = P.ProductID
GROUP BY SOD.[ModifiedDate]
, PC.[Name]
, PSC.[Name]
, P.[Name]

ORDER BY  5 DESC



No comments:

Post a Comment