选择第二个最大日期 - 多个记录

时间:2016-12-21 12:31:00

标签: mysql max

我需要通过在一个结果集中同时选择MAX(Date)和SECONDMAX(DATE)来整理数据集。

然而,数据源包含多个记录,这些记录将具有许多不同的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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_date的最大和最大entity_codeOFFSET。我们可以将ORDER BYsnd_pcm_delay子句一起使用,以获得第二个最大日期。

Demo here