This should be easy if your RDBMS supports Window Functions
SELECT ProductID,
Name,
TheYear,
OrderQty,
OrderAmount
FROM
(
SELECT DP.ProductID
,DP.Name
,Year(FS.OrderDate) as TheYear
,FS.OrderQty
,FS.OrderAmount,
,ROW_NUMBER() OVER() (PARTITION BY Year(FS.OrderDate)
ORDER BY FS.OrderQty DESC) rn
FROM dbo.DimProduct AS DP
LEFT JOIN dbo.FactSales as FS
on FS.ProductID = DP.ProductID
) s
WHERE rn <= 10
ORDER BY TheYear
The current query will give you 10
products for every TheYear
based on FS.OrderQty
since you have not mentioned the criteria on how the records will be sorted out.
The ROW_NUMBER()
(a RANKING function) will generate a sequence of number for each group, in this case Year(FS.OrderDate)
, that is sorted out based on FS.OrderQty
. The records will then be filtered out based on the value of the generated sequence.
However, if ROW_NUMBER()
will not generate TIE
on the records having the same FS.OrderQty
. If you want it to be handled, use DENSE_RANK()
instead of ROW_NUMBER()
.