Question

I am trying to filter a SSRS report to show the top 20 items sold at each location for multiple locations. I have the query pull all items sold sorted by desc sum(quantity), and also have the query pull the row number thinking I could filter in SSRS to the top 20 row number. The problem is that this filters the entire data set instead of per location.

Query:

SELECT
  [Location]
  ,[Item No_]
  ,sum(-[Quantity]) as TotalQuantity
  ,ROW_NUMBER() OVER (PARTITION BY [Location Code] ORDER BY sum(-[Quantity]) DESC) AS RN
FROM [Ledger Entry]
  left join [Item] i on  [Ledger Entry].[Item Number] = i.No_
  WHERE 
  [Date] BETWEEN @StartDate and @EndDate
  GROUP BY 
  [Location Code]
  ,[Item No_] 

Sorry if the code is bad, I am pretty new to SQL.

Was it helpful?

Solution

You have the base of the query in the code above. This should give you a count 1 to n for each location. This becomes the sub query that you select the records from. Example below:

SELECT  [Location] ,[Item No_] ,TotalQuantity

FROM
(
SELECT
     [Location]
    ,[Item No_]
    ,sum(-[Quantity])                       AS  TotalQuantity
    ,ROW_NUMBER()
        OVER (PARTITION BY [Location Code] 
        ORDER BY sum(-[Quantity]) DESC)     AS RN
FROM 
    [Ledger Entry]

    LEFT JOIN [Item] i 
    ON  [Ledger Entry].[Item Number] = i.No_
WHERE 
  [Date] BETWEEN @StartDate and @EndDate
GROUP BY 
   [Location Code]
  ,[Item No_] 
) AS SubQuery

WHERE RN <= 20

Passing this limited result set to SSRS will give you only the top 20 items per location. Its generally better for performance to limit and filter in the Data Query rather than in SSRS.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top