I have a schema as following:
Products(name, company_id, version)
Adding some dummy data:
name | company_id | version |
---|---|---|
a | 1 | 1 |
b | 1 | 1 |
a | 1 | 2 |
c | 2 | 1 |
a | 2 | 1 |
I want to find all the rows which have name=a
, company_id=1
and the version is latest.
I looked at Fetch the row which has the Max value for a column and build a query as following
SELECT * FROM Products p
WHERE p.name = a AND p.company_id = 2 AND p.version =
(SELECT MAX(q.version) FROM Products q
WHERE q.name = a AND q.company_id = 2)
Is there any better way in which these type of queries can be designed? I'm using SQL Server 2014.