如何在具有多个VID和其他字段的表中仅选择具有最大VID的行?

时间:2019-02-19 13:37:54

标签: sql-server tsql group-by

我在SQL Server中有一个视图,该视图为我提供了一些游戏的记录。它返回多个属于一个游戏的记录,它们具有相同的Gid,但不同的版本具有不同的Vids,如下所示

vid gid otherData(Platform)
2   1   PC
2   1   PC ...
3   1   X1
3   1   X2....
2   5   PC
2   5   PC ...
3   5   X1
3   5   X2....

如何使用分组依据并选择或仅通过其他方式选择这些记录?

3   1   X1
3   1   X2....
3   5   X1
3   5   X2....

2 个答案:

答案 0 :(得分:3)

您想要dense_rank()

select top (1) with ties t.*
from table t
order by dense_rank() over (partition by gid order by vid desc);

编辑:

select t.*
from (select t.*,
             dense_rank() over (partition by gid order by vid desc) as seq
      from table t
     ) t
where seq = 1;

答案 1 :(得分:1)

使用GROUP BY的解决方案:

  • 使用CTE:

    ;WITH HighestVIDByGID AS
    (
        SELECT
            V.gid,
            MaxVid = MAX(V.vid)
        FROM
            vYourView AS V
        GROUP BY
            V.gid
    )
    SELECT
        V.*
    FROM
        vYourView AS V
        INNER JOIN HighestVIDByGID AS M ON 
            V.gid = M.gid AND
            V.vid = M.MaxVid
    
  • INNER JOIN与子查询一起使用:

    SELECT
        T.*
    FROM
        vYourView AS T
        INNER JOIN (
                SELECT
                    V.gid,
                    MaxVid = MAX(V.vid)
                FROM
                    vYourView AS V
                GROUP BY
                    V.gid
            ) AS M ON
                T.gid = M.gid AND
                T.vid = M.MaxVid
    
  • 使用EXISTS

    SELECT
        T.*
    FROM
        vYourView AS T
    WHERE
        EXISTS (
            SELECT
                'max vid version'
            FROM
                vYourView AS V
            GROUP BY
                V.gid
            HAVING
                T.gid = V.gid AND
                T.vid = MAX(V.vid))