Answer the question
In order to leave comments, you need to log in
How to select the last value by date and the previous one in the same row?
There is a table:
id date balance
Its approximate content:
id date balance
1 2018-10-01 111
1 2018-10-02 115
12 2017-10-01 1134
... и тд
id date_current balance current_balance date_previous_balance previous balance
SELECT
id,
date,
balance
FROM (
SELECT
cb.*,
row_number() OVER (PARTITION BY id ORDER BY date DESC) r
FROM client_balance cb
) t
WHERE r = 1
;
Answer the question
In order to leave comments, you need to log in
You apparently never read and looked at how ROW_NUMBER works from the answer to the previous question !?
see the query output with ROW_NUMBER() !
SELECT
b.*,
row_number() OVER (PARTITION BY id ORDER BY balance_date DESC) r
FROM balance b
Therefore, you just need to choose with r = 1 or r =2 , respectively!
WITH bal AS (
SELECT
b.*,
row_number() OVER (PARTITION BY id ORDER BY balance_date DESC) r
FROM balance b
)
SELECT id, balance_date, balance FROM bal WHERE r = 1 or r = 2
ORDER BY id, balance_date desc
;
WITH
bal AS (
SELECT
b.*,
row_number() OVER (PARTITION BY id ORDER BY balance_date DESC) r
FROM balance b
),
last_bal AS (
SELECT id, balance_date, balance FROM bal WHERE r = 1
),
prev_bal AS (
SELECT id, balance_date, balance FROM bal WHERE r = 2
)
SELECT
lb.id,
lb.balance_date AS last_balance_date, lb.balance AS last_balance,
pb.balance_date AS prev_balance_date, pb.balance AS prev_balance
FROM last_bal lb
LEFT JOIN prev_bal pb ON pb.id = lb.id
;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question