I am trying to write a query that will group by different combination of certain columns and give me 'N
' records for each combination of the columns. I have been able to categorize it using a single column, but I am unable to get the grouping correct when it involves multiple columns. Below is an example of how the data in the table looks like and the output I am expecting. Here 'N' = 2
.
Expected output :
- max 2 records for each unique combination of columns
- which 2 records are selected is not important.
- If there are
< N
records, then return all rows (i.e the no of records should not exceed'N'
, but can be<N
UPDATE : Was able to get the desired output. My question now is - if there is any further efficient way to do it, given I will need to run it on a table containing several columns and the number of combinations will quickly increase.
WITH SUBSET AS (
SELECT [ServerName],[SKU],[Feature1],[Feature2],[Feature3],ROW_NUMBER() OVER (
PARTITION BY [SKU], [Feature1], [Feature2],[Feature3] order by [ServerName]) AS [ROW NUMBER]
FROM [tablename]
)
SELECT ServerName ,SKU ,Feature1 ,Feature2 ,Feature3 FROM [SUBSET]
WHERE [SUBSET].[ROW NUMBER] <= 2