[Solved] How to get second MAXIMUM DATE in MYSQL


It wasn’t fun to read your query, but I think the problem is here:

LEFT JOIN (
  SELECT max(notification_date) notification_date, client_id
  FROM og_ratings
  WHERE notification_date NOT IN (
    SELECT max(notification_date)
    FROM og_ratings
)

if you want the maximum date for every client you need to GROUP BY client_id:

SELECT client_id, max(notification_date) notification_date
FROM og_ratings
GROUP BY client_id

if you want the second maximum there are few options, I’m using this one which is easier to understand but it’s not necessarily the most performant:

SELECT client_id, max(notification_date) notification_date
FROM og_ratings
WHERE
  (client_id, notification_date) NOT IN (
    SELECT client_id, max(notification_date)
    FROM og_ratings GROUP BY client_id
  )
GROUP BY client_id

third problem, you’re using a LEFT JOIN which means that you will return all values from og_ratings regardless if they are the second maximum or not. Use INNER JOIN on this context:

SELECT
  r.client_id,
  c.id,
  t.id,
  ..etc...
FROM
  og_ratings r INNER JOIN (
    SELECT client_id, max(notification_date) notification_2nd_date
    FROM og_ratings
    WHERE
      (client_id, notification_date) NOT IN (
        SELECT client_id, max(notification_date)
        FROM og_ratings GROUP BY client_id
      )
    GROUP BY client_id
   ) r2
  ON r.notification_date = r2.notification_2nd_date
     AND r.client_id = r2.client_id
  LEFT JOIN og_companies c ON r.client_id = c.id
  LEFT JOIN og_rating_types t ON r.rating_type_id = t.id
  LEFT JOIN og_actions a ON r.pacra_action = a.id
  LEFT JOIN og_outlooks o ON r.pacra_outlook = o.id
  LEFT JOIN og_lterms l ON r.pacra_lterm = l.id
  LEFT JOIN og_sterms s ON r.pacra_sterm = s.id
  LEFT JOIN pacra_client_opinion_relations pr ON pr.opinion_id = c.id
  LEFT JOIN pacra_clients pc ON pc.id = pr.client_id
  LEFT JOIN city ON city.id = pc.head_office_id
WHERE
  r.client_id IN (
    SELECT opinion_id FROM pacra_client_opinion_relations
    WHERE client_id = 50
  )

3

solved How to get second MAXIMUM DATE in MYSQL