Wednesday, November 20, 2019

SQL Server: Select the first / least / max row per group or category

In case of table data, if users want to select the records based on the specific criteria i.e. get one row per category / group from the table, then this can be achieved using the following query:

E.g You have a table "Items" having columns Id,ItemName,Type and Price


Select * FROM
(
Select *,
Row_Number() over (partition by [type] order by Price ASC) as RowN
FROM Items
) T Where RowN <=1

The above query returns the records with least price from each type in the table. Although the default sorting set in the SQL is ascending, but this is added for better understanding.

Thanks.



Tuesday, May 14, 2019