This can be resolved using a simple row_number
and top 1 with ties
.
First, create and populate sample table (Please save us this step in your future questions)
DECLARE @customer AS TABLE
(
fileid int,
orderid int,
customername varchar(20)
);
INSERT INTO @customer (fileid, orderid, customername) VALUES
(1, 1, 'Marshall, John'),
(1, 2, 'Mary, Rose'), -- Shuold be selected
(2, 3, 'Marvis, Emma'),
(2, 4, 'Miller, Ross'), -- Shuold be selected
(4, 1, 'Saraf, Ram'), -- Shuold be selected
(5, 2, 'Miller, Katie'),
(5, 3, 'Miller, Abby'),
(5, 4, 'Wolowiz, Andy'); -- Shuold be selected
The query:
SELECT TOP 1 WITH TIES fileid, orderid, customername
FROM @Customer
ORDER BY ROW_NUMBER() OVER(PARTITION BY fileid ORDER BY orderid DESC)
Results:
fileid orderid customername
1 2 Mary, Rose
2 4 Miller, Ross
4 1 Saraf, Ram
5 4 Wolowiz, Andy