2016-12-21 124 views
-1

我需要通過在一個結果集中選擇MAX(日期)和SECONDMAX(日期)來整理數據集。選擇第二個最大日期 - 多個記錄

但是,數據源包含多個記錄,其中將包含多個不同的MAX/SECONDMAX日期。

每條記錄​​都有一個唯一的實體代碼,這就是我如何確定哪一組日期屬於哪個實體。

我已經寫了下面的查詢,但我不斷收到一條消息說

「錯誤代碼:1111無效使用組功能的

SELECT 
    entity_code 'Entity Code', 
    (SELECT MAX(visit_date) 
    FROM z_dev.entities_visited A 
    WHERE visit_date < (SELECT MAX(visit_date) 
         FROM z_dev.entities_visited D 
         WHERE D.entity_code = A.entity_code) AND 
          C.entity_code = A.entity_code), 
    (SELECT MAX(visit_date) 
    FROM z_dev.entities_visited B 
    WHERE visit_date = MAX(visit_date) AND C.entity_code = B.entity_code), 
    cycle_end_date 
FROM z_dev.entities_visited C 
GROUP BY entity_code; 

樣本數據

entity_code | visit_date | cycle_end_date 
------------+------------+--------------- 
108792  |2016-12-07 |2016-12-11  
108793  |2016-12-08 |2016-12-11  
108795  |2016-12-06 |2016-12-11  
108796  |2016-12-05 |2016-12-11  
108795  |2016-12-13 |2016-12-18  
108792  |2016-12-14 |2016-12-18  
108793  |2016-12-14 |2016-12-18  
108796  |2016-12-16 |2016-12-18 
+0

給我們一些示例數據http://sqlfiddle.com/ –

+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for什麼似乎對我來說是一個非常簡單的SQL查詢 – Strawberry

回答

1

根據我的理解,您希望獲得每個月的最大日期和第二個最大日期entity_code。對下面的可以幫助你

SELECT x.entityCode 'Entity Code', 
    x.maxDate, 
    (SELECT MAX(visit_date) AS secMaxDate FROM z_dev.entities_visited 
     WHERE entity_code=x.entityCode AND visit_date<x.maxDate), 
    cycle_end_date 
FROM 
    (SELECT entity_code AS entityCode,MAX(visit_date) AS maxDate 
    FROM z_dev.entities_visited GROUP BY entity_code) AS X 
+0

謝謝,正是我在找什麼。我現在想補充的是在過去的28天裏這個實體訪問的次數。 –

1

試試這個:

SELECT 
    entity_code 'Entity Code', 
    -- Correlated subquery to get the MAX date 
    (SELECT MAX(visit_date) 
    FROM entities_visited A 
    WHERE A.entity_code = C.entity_code) AS max_visit_date, 
    -- Correlated subquery to get second the MAX date 
    (SELECT visit_date 
    FROM entities_visited B 
    WHERE B.entity_code = C.entity_code 
    ORDER BY visit_date DESC LIMIT 1 OFFSET 1) AS max_visit_date2 
FROM entities_visited C 
GROUP BY entity_code; 

查詢,以獲取最大和第二最大visit_dateentity_code使用相關子查詢。我們可以使用OFFSETORDER BY條款來獲得第二個最大日期。

Demo here