从不使用LIMIT

时间:2017-01-29 23:15:48

标签: sql postgresql excel-vba vba excel

我在Excel VBA中使用以下SQL代码从PostGreSQL导入数据:

Const sqlconnection = "Provider=visoledb;"

Dim conn As New Connection
conn.ConnectionString = sqlconnection
conn.Open
Dim rs As Recordset

Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "FR"
Sheets("FR").Select
Range("A1").Select

DIm fr As String
    fr = "SELECT master_id, eventdate, num_result " _
    & "FROM fr INNER JOIN person p ON fr.master_id=p.entity_id AND p.auditflag=1 " _
    & "WHERE fr.auditflag=1 AND num_result IS NOT NULL AND num_result <> 0 " _
    & "ORDER BY master_id "  

Set rs = conn.Execute(fr)
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
    .Refresh
End With

rs.Close

它为我提供了表格中每个人的所有记录值。

我被告知我无法使用LIMIT,所以如何限制它只显示每个人的最后5条记录。

2 个答案:

答案 0 :(得分:0)

使用row_number()

SELECT master_id, eventdate, num_result 
FROM fr INNER JOIN
     (SELECT p.*,
             ROW_NUMBER() OVER (PARTITION BY p.entity_id ORDER BY ?? DESC) as seqnum
      FROM person p
     ) p
     ON fr.master_id = p.entity_id AND p.auditflag = 1 AND seqnum <= 5
WHERE fr.auditflag = 1 AND num_result IS NOT NULL AND
      num_result <> 0
ORDER BY master_id;

我不知道你如何定义&#34;最后5&#34;。指定它的列是??引用的内容。

答案 1 :(得分:0)

假设有一对多联接的规范化数据库与不同的有多个 fr 记录,并且需要显示每个人的最后5条记录表示时间元素,因此建议fr.eventdate字段,请考虑Postgres&#39; ROW_NUMBER()窗函数。

具体而言,此ROW_NUMBER()按降序f.masterid计算按外键eventdate(即每个人ID)分组的记录顺序。有了这样的排名,您就可以在外部查询的WHEREON子句中过滤前5位:

SELECT t.master_id, t.eventdate, t.num_result
FROM 
    (
     SELECT fr.master_id, fr.eventdate, fr.num_result, 
            ROW_NUMBER() OVER (PARTITION BY fr.master_id ORDER BY fr.eventdate DESC) AS rnk
     FROM fr
     WHERE fr.auditflag=1 AND fr.num_result <> 0 AND fr.num_result IS NOT NULL
    ) As t

INNER JOIN person p
   ON t.master_id = p.entity_id AND p.auditflag=1 
WHERE t.rnk <= 5
ORDER BY master_id, t.eventdate;