I'm trying to solve a problem in SQL but without much success so far. I have a table like this:
OWNER|STORE|DATE
A | MIX |01/01/2019
A | BIX |01/01/2019
A | BIX |02/01/2019
B | CIX |01/01/2019
B | CIX |02/01/2019
It's a table showing information about owners and their stores. An owner can have a store during a month, but this store could be gone in the next month. Or, their store could be present in january, but gone in february.
I wanted to find a way to flag this store movement, so if a store is present in january, and gone in february, I would flag a colum as "gone". And if a store was not present in january, but appeared in february, I would flag it as "new".
Can anyone help me with that? Thanks!
select d.store ,d.owner , d.timedate , 'new' flag from (
SELECT
a.store, count(a.store) as flag
FROM
store as a
left join store as b
on a.store=b.store
group by a.store
having(count(a.store)<2)) as c
inner join store as d
on c.store=d.store
union all
(SELECT
a.store , a.owner, max(a.timedate ), 'gone' as [flag]
FROM
store as a
inner join
(SELECT
owner,store,timedate
FROM store) as b
on b.store = a.store and a.timedate!=b.timedate
group by a.store , a.owner)
sqlfiddle here