Answer the question
In order to leave comments, you need to log in
How to select the latest value by date from a group of rows?
There is a table: client id, date of the beginning of the month, date of the middle of the month, balance of the beginning of the month, balance of the middle of the month.
id are not unique, those 1 client occurs several times.
id, balance_date_start, balance_start, balance_date_mid, balance_mid
select distinct id, BALANCE_DATE_start, BALANCE_start, BALANCE_DATE_mid, BALANCE_DATE_mid from table
where BALANCE_DATE_start in (
select max (BALANCE_DATE_start) from table)
group by ID
id BALANCE_DATE_start BALANCE_start BALANCE_DATE_mid BALANCE_DATE_mid
676 2021-10-02 255 2021-10-17 255
155 2021-10-02 222 2021-10-15 197
676 2021-09-01 211 2021-09-14 333
155 2021-11-01 159 2021-11-15 104
Answer the question
In order to leave comments, you need to log in
see ROW_NUMBER
SELECT
id,
balance_date_start,
balance_start,
balance_date_mid,
balance_mid
FROM (
SELECT
cb.*,
row_number() OVER (PARTITION BY id ORDER BY balance_date_start DESC) r
FROM client_balance cb
) t
WHERE r = 1
;
Maybe that will fit?
CREATE TABLE client_balance
(
id SMALLINT AUTO_INCREMENT,
id_client INTEGER,
balance_date_start DATETIME,
balance_start INTEGER,
balance_date_mid DATETIME,
balance_mid INTEGER,
PRIMARY KEY (id)
);
SELECT cb.*,
DATEDIFF(cb.balance_date_mid, cb.balance_date_start) AS diff
FROM client_balance AS cb
GROUP BY cb.id_client
HAVING MAX(diff);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question