选择所有类型的记录' x'这是最高的版本'

时间:2015-06-24 21:19:58

标签: sql postgresql greatest-n-per-group

给出表:

Sub ChangeTableLink()

    Dim sNewPath As String
    Dim lDbaseStart As Long
    Dim td As TableDef
    Dim sFile As String
    Dim db As DAO.Database

    'This is what we look for in the Connect string
    Const sDBASE As String = "DATABASE="

    'Set a variable to CurrentDb and to the table
    Set db = CurrentDb
    Set td = db.TableDefs("Fuel Pricing")

    'Whatever your new path is, set it here
    sNewPath = CurrentProject.Path & "\"

    'Find where the database piece starts
    lDbaseStart = InStr(1, td.Connect, sDBASE)

    'As long as you found it
    If lDbaseStart > 0 Then
        'Separate out the file name
        sFile = Dir(Mid(td.Connect, lDbaseStart + Len(sDBASE), Len(td.Connect)))

        'Rewrite Connect and refresh it
        td.Connect = Left(td.Connect, lDbaseStart - 1) & sDBASE & sNewPath & sFile
        td.RefreshLink
    End If

End Sub

鉴于记录如下:

Agreement:
    id: int
    type: string
    version: int

我想要一个输出的查询:

1 | Terms | 1
2 | Terms | 2
3 | Privacy | 1

我已尝试过各种各样的独特和自我联接到max(版本),我似乎无法破解它。

4 个答案:

答案 0 :(得分:3)

最简单的事情可能是使用rank窗口函数:

SELECT id, type, version
FROM   (SELECT id, type, version, 
               RANK() OVER (PARTITION BY type ORDER BY version DESC) AS rk
        FROM   agreement) t
WHERE  rk = 1

答案 1 :(得分:2)

应该有效:

 select max(id) , type , max(version) from Agreement
 group by type

答案 2 :(得分:1)

试试这个:

SELECT a.id, a.type, a.version
FROM Agreement AS a
INNER JOIN (SELECT type, MAX(version) AS maxV
            FROM Agreement
            GROUP BY type) t 
ON t.type = a.type AND a.version = t.maxV

此查询使用包含每MAX(version) type的派生表。加入此派生表,我们可以获得原始表的所有行,每个行具有type的最大版本。

Demo here

答案 3 :(得分:0)

PostgreSQL的:

从协议中选择*其中id为(从协议b中选择id,其中a.type = b.type order by id desc limit 1)

结果:

2 |条款| 2

3 |隐私| 1

相关问题