-4

Starting from this query

SELECT DISTINCT Name,Manufacturer,Model,RevisionID FROM dbo.COMPUTER_TABLE ORDER BY Name,RevisionID

I get to the following table:

(Name,Manufacturer,Model,RevisionID)

UST8923 | Microsoft | Surface 2 | 1
UST8923 | Microsoft | Surface 2 | 2
UST8923 | Microsoft | Surface 3 | 3
UST8923 | Microsoft | Surface 3 | 4
CAD4258 | Lenovo | Thinkpad P1 | 1
CAD4258 | Lenovo | Thinkpad P1 | 2
CAD4258 | Dell | Latitude 5480 | 3

I need to get only the records with the highest RevisionID and discard the rest. So, I need to get this result:

UST8923 | Microsoft | Surface 3 | 4
CAD4258 | Dell | Latitude 5480 | 3

Any ideas?

  • If you only need those four columns you can group by `Name,Manufacturer,Model` and apply `max(RevisionID)`. Otherwise do `row_number() over (partition by Name,Manufacturer,Model order by RevisionID desc) as rn` in a CTE and filter `where rn = 1` – dnoeth Jan 08 '19 at 19:08

2 Answers2

1

A correlated subquery is a simple and efficient solution:

select ct.*
from dbo.COMPUTER_TABLE ct
where ct.revisionid = (select max(ct2.revisionid)
                       from COMPUTER_TABLE ct2
                       where ct2.name = ct.name
                      );
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

You need to GROUP BY Name, Manufacturer

SELECT 
  Name,
  Manufacturer, 
  MAX(Model) AS MaxModel,
  MAX(RevisionID) AS MaxRevisionID 
FROM dbo.COMPUTER_TABLE 
GROUP BY Name, Manufacturer
ORDER BY Name, MAX(Model), MAX(RevisionID)
forpas
  • 160,666
  • 10
  • 38
  • 76