sql >> Base de Datos >  >> RDS >> Mysql

Cómo obtener registros en función de las fechas en MYSQL

Usa ROW_NUMBER() función de ventana para obtener la fila con Run_amt del mes máximo y luego con agregación condicional:

SELECT t.ID, t.Name, t.Amount,
  MAX(CASE WHEN LAST_DAY(Date) = LAST_DAY(CURRENT_DATE) THEN cal_amt END) cal_amt,
  MAX(CASE WHEN t.rn = 1 THEN Run_amt END) Run_amt
FROM (
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY ID, Name, Amount ORDER BY Date DESC) rn
  FROM tablename
) t
GROUP BY t.ID, t.Name, t.Amount

O:

SELECT t.ID, t.Name, t.Amount,
       MAX(t.cal_amt) cal_amt,
       MAX(t.Run_amt) Run_amt
FROM (
  SELECT ID, Name, Amount,
    MAX(CASE WHEN LAST_DAY(Date) = LAST_DAY(CURRENT_DATE) THEN cal_amt END) 
      OVER (PARTITION BY ID, Name, Amount ORDER BY Date DESC) cal_amt,
    FIRST_VALUE(Run_amt) OVER (PARTITION BY ID, Name, Amount ORDER BY Date DESC) Run_amt
  FROM tablename
) t  
GROUP BY t.ID, t.Name, t.Amount

Vea la demostración .
Resultados:

> ID | Name   | Amount | cal_amt | Run_amt
> -: | :----- | -----: | ------: | ------:
>  1 | Test   |  15000 |   12000 |   15000
>  2 | Test_1 |  18000 |   16000 |   25000