简体   繁体   English

SQL组的基本用法

[英]Basic usage of SQL group

A very basic question if this can be done using Group by in SQL Server. 一个非常基本的问题,如果可以在SQL Server中使用Group by完成。

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 使用Group By ID, max(Version)我得到Group By ID, max(Version)

ID    Version
--------------
123   3
158   4

I have an extended table with another column value , which is the interesting data: 我有一个扩展表与另一个列value ,这是有趣的数据:

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 ? 这是否可以通过使用Group By

You can solve that with an INNER JOIN with a SUBQUERY. 您可以使用带有SUBQUERY的INNER JOIN来解决这个问题。 I don't know your table names but lets call them VersionTable and VersionValueTable. 我不知道你的表名,但我们称之为VersionTable和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. 您不要使用group by The most common approach is row_number() : 最常见的方法是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: 如果您正在学习窗口函数,则最靠近该group by是:

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 . 您可以将行的版本与属于每个行ID的Max-version进行比较。 With a subquery you can find the subset of rows that have the same ID and get the maximum value of Version field. 使用子查询,您可以找到具有相同ID的行的子集,并获取Version字段的最大值。 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. 要查找与主Select查询中当前行具有相同id的记录子集,可以使用whereclause(WHERE t2.id = t1.id),其中t1是主查询中表的别名,t2是子查询中表的别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM