A very basic question if this can be done using Group by
in SQL Server.
I have a table like this:
ID Version
-------------
123 1
123 3
158 1
158 2
158 4
using Group By ID, max(Version)
I get
ID Version
--------------
123 3
158 4
I have an extended table with another column value
, which is the interesting data:
ID Version Value
----------------------
123 1 abc
123 3 xyz
158 1 pq
158 2 je
158 4 kju
I want to retrieve
ID Version Value
----------------------
123 3 xyz
158 4 kju
I fail to get the value as shown above. Is this possible by using Group By
?
You can solve that with an INNER JOIN with a SUBQUERY. I don't know your table names but lets call them VersionTable and VersionValueTable. So I would do this:
SELECT vt.ID, vt.Version, vvt.Value
FROM VersionValueTable vvt
INNER JOIN (SELECT ID, MAX(Version)
FROM VERSION
GROUP BY ID) vt ON vt.ID = vvt.ID AND vt.Version = vvt.Version
You don't use group by
for this. The most common approach is row_number()
:
select t.*
from (select t.*,
row_number() over (partition by id order by version desc) as seqnum
from t
) t
where seqnum = 1;
There are a zillion other ways to do this. If you are learning about window functions, the closest to the group by
is:
select t.*
from (select t.*,
max(verson) over (partition by id) as max_version
from t
) t
where version = max_version;
You can compare version of rows with Max-version that belongs to each row ID . With a subquery you can find the subset of rows that have the same ID and get the maximum value of Version field. As you see in the following code :
SELECT * FROM MyTable t1
WHERE t1.version =
(SELECT max(version) FROM MyTable t2 WHERE t2.id = t1.id)
To find a subset of records, that have the same id as the current row in main Select query , you can use a whereclause ( WHERE t2.id = t1.id ) where t1 is alias for our table in main query and t2 is the alias for the table in subquery.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.