How To Display Value by Max Date / Last Date of Year

422 views Asked by At

I need a query to display a value (saldo) following max date / the last date of year, but I have tried but it and it's always showing a value from the first date.

Here is my query:

SELECT saldo, MAX(tgl_lap) FROM laporan GROUP BY DATE_FORMAT(tgl_lap,'%Y','%m') ORDER BY DATE_FORMAT(tgl_lap,'%Y','%m') DESC

my result:

enter image description here

And my expectated result should be only showing values like in the red box below:

enter image description here

2

There are 2 answers

3
Akina On
WITH cte AS ( 
    SELECT *, ROW_NUMBER() OVER (PARTITION BY YEAR(tgl_lap) ORDER BY tgl_lap DESC) rn
    FROM laporan 
    )
SELECT *
FROM cte
WHERE rn = 1
1
Nasir Abbas On
select * 
From laporan t
where t.tgl_lap = 
(
  select max(a.tgl_lap) 
  from laporan a 
  where year(t.tgl_lap) = year(a.tgl_lap)
)

According to the sample data, considering there would be only one record per date, the sub query will return max date of the year and main query will return complete record of the last or max date of the year.