Joe
Joe

Reputation: 13091

SQL - How to get only current and previous value for each ID

I have a table

id, date, value
a,  5/22/2019, 22
b,  5/22/2019, 22
c,  5/22/2019, 22
a,  5/21/2019, 21
b,  5/21/2019, 21
c,  5/21/2019, 21
a,  5/20/2019, 20
b,  5/20/2019, 20
c,  5/20/2019, 20

Want to get ID and value of current (latest) and previous date:

id, date, date-1
a, 22, 21
b, 22, 21
c, 22, 21

So far I have some parts but need only 1 ID per row (this bellow give more than 1 row for each ID - it will show for 5/20 date in the next row for the same ID which is wrong):

select 
    id, value,
    lag(value, 1, 0) over (partition by id order by date ) as "date - 1"
from 
    table1

How to achieve that?

Upvotes: 3

Views: 988

Answers (2)

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

you can try like below

with cte as
(
select 
    id, value,
    lag(value, 1, 0) over (partition by id order by date ) as "date - 1",
    lag(value, 2, 0) over (partition by id order by date ) as "date - 2",
    row_number() over(partition by id order by date desc) rn
from 
    table1
) select * from cte where rn=1

Upvotes: 2

Simon
Simon

Reputation: 1211

How about this? Note that I named the column ddate instead of date:

create table a_test(id varchar(1), ddate date, value int);

insert into a_test values ('a',  '5/22/2019', 22),
                          ('b',  '5/22/2019', 22),
                          ('c',  '5/22/2019', 22),
                          ('a',  '5/21/2019', 21),
                          ('b',  '5/21/2019', 21),
                          ('c',  '5/21/2019', 21),
                          ('a',  '5/20/2019', 20),
                          ('b',  '5/20/2019', 20),
                          ('c',  '5/20/2019', 20);

with cte as(
select id,
       value,
       row_number() over(partition by id order by ddate desc) as rn
from a_test)

select id,
       MAX(value) FILTER (WHERE rn = 1) as col1,
       MAX(value) FILTER (WHERE rn = 2) as col2
from cte
group by id

Upvotes: 2

Related Questions