sql >> Database teknologi >  >> RDS >> Mysql

Sådan får du den anden MAKSIMUM DATO i MYSQL

Det var ikke sjovt at læse din forespørgsel, men jeg tror, ​​problemet er her:

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
)

hvis du vil have den maksimale dato for hver klient, skal du GRUPPERE BY client_id:

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

hvis du vil have det andet maksimum, er der få muligheder, jeg bruger denne, som er nemmere at forstå, men den er ikke nødvendigvis den mest effektive:

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

tredje problem, du bruger en LEFT JOIN, hvilket betyder, at du returnerer alle værdier fra og_ratings, uanset om de er det andet maksimum eller ej. Brug INNER JOIN i denne sammenhæng:

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
  )


  1. Opret en dato fra dag måned og år med T-SQL

  2. ORACLE Connect by klausul tilsvarende i SQL Server

  3. MySql i DNX 5.0

  4. Sådan viser du en dato i amerikansk datoformat i SQL Server (T-SQL)