Joe
Joe

Reputation: 13111

SQL - join with itself

I have a table t1 as below

 -----------------------------
 |    date   |  id   | value |
 -----------------------------
 | 2/28/2019 |  1    | abc1  |
 | 2/28/2019 |  2    | abc2  |
 | 2/28/2019 |  3    | abc3  |
 | 2/27/2019 |  1    | abc4  |
 | 2/27/2019 | 2     | abc5  |
 | 2/27/2019 | 3     | abc3  |
 -----------------------------

I want to take abc3 from t1 and then find abc3 value for date - 1 day in the same table t1 and display both records.

In this case it would be 2 records:

-------------------------------
| date      | id   |  value   |
-------------------------------
| 2/28/2019 |  3   |  abc3    |
| 2/27/2019 |  3   |  abc3    |
-------------------------------

How to achieve that? Thanks.

Upvotes: 0

Views: 93

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269933

Is this what you want?

select t.* 
from t
where value = 'abc3'
order by date desc
limit 2;

Or, do you want to find abc3 because the value is the same on two consecutive days?

select t.* 
from t
where value = 'abc3' and
      exists (select 1
              from tablename t2
              where t2.value = t.value and
                    t2.date in (t.date - interval 1 day, t.date + interval 1 day) 
             );

Upvotes: 1

forpas
forpas

Reputation: 164099

You can use EXISTS:

select t.* 
from tablename t
where
  value = 'abc3'
  and 
  exists (
    select 1 from tablename
    where value = 'abc3' and date in (t.date - INTERVAL 1 DAY, t.date + INTERVAL 1 DAY) 
  )

See the demo.

Upvotes: 1

Related Questions