Sunday, June 29, 2014

Based on the parameter to find Top 5 and Bottom 5 Sales in a single query in SQL


Declare @sort bit = 0;

select * from
(
select R.EnglishProductName,
       R.salesamount,
       case when @sort = 1 then RANK()over (order by salesamount desc)
            when @sort = 0 then RANK()over (order by salesamount ASC) end rsales
       from
(
select distinct dp.EnglishProductName,
sum(fr.SalesAmount) over (Partition by dp.EnglishProductName) as salesamount
from dbo.DimProduct DP
INNER JOIN dbo.FactResellerSales FR
ON DP.ProductKey = FR.ProductKey
)R
)T where rsales <= 5 order by rsales