Skip to content
Advertisement

Select most recent row filtered on multiple columns

I have an sql table

I’m trying to get write an SQL statement or preferably LINQ to get the most recent row by date then max row number for each part at each location

Expected results:

I’m not sure on how to include multiple locations for the same part It will put in to the following class

I haven’t tried in LINQ yet because I’m work-shopping it in sql

Advertisement

Answer

In SQL Server, use ROW_NUMBER():

NB: it is unclear to me what kind of sorting you expect with rowID, since you stated that you want records sorted by Inventory_Date: I used it as a second sort criteria (hence it will break top ties on Inventory_Date if needed).

Demo on DB Fiddle:

rowID | location | fk_Item_ID | Balance | Inventory_Date      | rn
----: | -------: | :--------- | ------: | :------------------ | :-
    2 |        1 | p2         |     450 | 05/01/2019 00:00:00 | 1 
    3 |        2 | p2         |     500 | 10/01/2019 00:00:00 | 1 
    5 |        1 | p1         |     350 | 16/01/2019 00:00:00 | 1 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement