DATE | ACCOUNT | VALUE |
---|---|---|
2023-06-06 | 1234 | 100 |
2023-06-07 | 1234 | 120 |
2023-06-08 | 1234 | 80 |
2023-06-06 | 3456 | 40 |
2023-06-07 | 3456 | 60 |
2023-06-08 | 3456 | 80 |
2023-06-05 | 5648 | 600 |
2023-06-06 | 5648 | 800 |
2023-06-06 | 5648 | 650 |
2023-06-07 | 5648 | 0 |
2023-06-08 | 5648 | 0 |
I’m passing current date and getting the latest value from the table.
set @curdate = '2023-06-08 ';
select DATE,ACCOUNT,
CASE WHEN DATE = @curdate THEN VALUE
WHEN VALUE = 0 AND DATE = @curdate THEN MAX(VALUE)
ELSE 0
END AS MAX_VALUE
from table ;
Actually I’m trying to get the latest value and for example if value is not present for current date then I have to get last maximum value for that account.
output :
DATE | ACCOUNT | VALUE |
---|---|---|
2023-06-08 | 1234 | 80 |
2023-06-08 | 3456 | 80 |
2023-06-06 | 5648 | 650 |
Can anyone suggest me on this one?
3
Answers
Using
ROW_NUMBER
we can try:On earlier versions of MySQL:
This can be done using this query :
The
cte
was used to get accounts with values, then we need to get the maximum value and the related date for accounts with value = 0, and finally we useunion all
to combine those datasets.Result :
Demo here
To get the first previous value that is not equal to 0,(when the value on
@curdate
is equal to 0 or not exists) we could use a subquery and aggregate as the following:Demo
Another approach, for mysql 5.7 you could simulate the row_number functionality as the following:
Demo