Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

encontre o máximo de conjunto de colunas para várias linhas na consulta mysql

SELECT
  *
FROM
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Year DESC, Month DESC) AS row_number,
    *
  FROM
    myTable
)
  AS orderedTable
WHERE
  row_number = 1




EDITAR E agora para uma versão que FUNCIONA no MySQL...
SELECT
  *
FROM
  myTable
WHERE
  Year * 12 + Month = (SELECT MAX(Year * 12 + Month) FROM myTable AS lookup WHERE Code = myTable.Code)

EDITAR Após o acesso ao SQL, posso confirmar que é mais rápido...
WHERE
    Year  = (SELECT MAX(Year)  FROM myTable AS lookup WHERE Code = myTable.Code)
AND Month = (SELECT MAX(Month) FROM myTable AS lookup WHERE Code = myTable.Code AND Year = myTable.Year)