2017-01-30 40 views
0

每個ID我需要找到的最後5個結果(通過EVENTDATE訂購)從測試表找到最後一個5個結果(通過EVENTDATE訂購)爲表

每一個標識的表中的示例圖像結構下面這是隻顯示從1個ID記錄,其中有數以千計的不同ID的所有與時間不同的結果,因此爲什麼我只希望最後5要返回

enter image description here

我有以下數據查詢幾乎是正確的,但它包括num_result = 0和auditflag = 2的計數爲< 6 (這當然是記在我的代碼是,我是新手)

SELECT q1.id, q1.eventdate, q1.num_result " _ 
     & "FROM test AS q1 INNER JOIN test AS q2 ON (q1.id = q2.id) " _ 
      & "AND (q1.eventdate <= q2.eventdate) AND q1.auditflag=1 " _ 
     & "WHERE q1.num_result > 0 " _ 
     & "GROUP BY q1.id, q1.eventdate, q1.num_result " _ 
     & "HAVING COUNT(*) < 6 " _ 
     & "ORDER BY q1.id, q1.eventdate DESC 

我只是想找到最後5個記錄是匹配即以黃色突出顯示 - 從那些具有num_result最後5個記錄> 0, auditflag = 1

SQL查詢是寫在Excel中使用VBA visoledb

回答

0

如果我理解正確連接到PG數據庫,這基本上是您查詢:

SELECT q1.id, q1.eventdate, q1.num_result 
FROM test q1 INNER JOIN 
    test q2 
    ON q1.id = q2.id AND 
     q1.eventdate <= q2.eventdate AND q1.auditflag = 1 
WHERE q1.num_result > 0 
GROUP BY q1.id, q1.eventdate, q1.num_result 
ORDER BY q1.id, q1.eventdate DESC ; 

我想你想這是你的基本的查詢:

SELECT q.id, q.eventdate, 
     SUM((q.auditflag = 1)::int) OVER (PARTITION BY q.id ORDER BY event_date) as num_result 
FROM test q; 

我想你想這與過濾器:

SELECT q.* 
FROM (SELECT q.id, q.eventdate, 
      SUM((q.auditflag = 1)::int) OVER (PARTITION BY q.id ORDER BY event_date DESC) as num_result 
    FROM test q 
    ) q 
WHERE num_result <= 5; 
+0

我越來越與1號線的「翻譯錯誤這兩個查詢的錯誤消息。。?意外的符號 – BradleyS

+0

@BradleyS是否指向查詢任何特別的地方沒有什麼明顯的錯誤,我可以看到 –

+0

它必須是VBA或者與PG的visoledb連接,它不會接受要使用的代碼的某些元素,雖然感謝您的幫助,但我想我將不得不嘗試使用VBA來實現這一點 – BradleyS

0

這種類型的查詢通常解決了window functions,如:

SELECT id, eventdate, num_result 
FROM  (SELECT id, eventdate, num_result, 
       row_number() OVER (PARTITION BY id ORDER BY eventdate) 
      FROM test 
      WHERE num_result > 0 
      AND auditflag = 1) q 
WHERE row_number <= 5 
ORDER BY id, eventdate DESC 

但是這肯定會導致整個桌子上的順序掃描。其中(如你所提到的)每id有成千上萬的行,你只需要最後5個行。這種分佈是更快地LATERAL subqueries查詢:

SELECT id, eventdate, num_result 
FROM  (SELECT DISTINCT id FROM test) q 
      -- above use a table where "id" is a unique (primary) key 
      -- f.ex. where "test.id" refers to if it's a foreign key 
LEFT JOIN LATERAL (SELECT eventdate, num_result 
        FROM  test 
        WHERE id = q.id 
        AND  num_result > 0 
        AND  auditflag = 1 
        ORDER BY eventdate DESC 
        LIMIT 5) l ON TRUE 

至於指標,一個id, eventdate DESC指數test將有很大的幫助(也,你可以把一個partialWHERE num_result > 0 AND auditflag = 1)。

0

儘管我不得不使用身份字段(這是全局auditsequence和唯一記錄標識符),但這是最終爲我工作的代碼。直到我問到爲什麼沒有任何工作時,我才知道這一點,但希望答案可以幫助其他人。感謝所有幫助我的人。

select id, eventdate, num_result 
from test 
where test.identity IN 
    (select top 5 identity from test as q1 
    where q1.id=test.id and q1.auditflag=1 and q1.num_result>0 
    order by q1.eventdate desc) 
order by id, eventdate desc 
+0

這個想法來自這裏:http://allenbrowne.com/subquery -01.html#TOPN。 – BradleyS