SQL - 检查某件商品在上个月是否有货,然后对其进行标记

SQL - Check if an item was available in the previous month and then flag it

我正在尝试解决 SQL 中的一个问题,但到目前为止还没有成功。我有一个 table 这样的:

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

这是一个 table 显示有关所有者及其商店的信息。所有者可以在一个月内拥有一家商店,但这家商店可能会在下个月消失。或者,他们的商店可能在 1 月存在,但在 2 月就消失了。

我想找到一种方法来标记此商店移动,因此如果一家商店在 1 月出现并在 2 月消失,我会将列标记为 "gone"。如果商店在 1 月不存在,但在 2 月出现,我会将其标记为 "new".

有人可以帮我吗?谢谢!

SELECT 
    ID, 
    OWNER, 
    STORE, 
    DATE, 
    CASE WHEN DATE IN (SELECT DATE FROM TableName
WHERE DATE IN (<InsertDatesHere)) THEN 'NEW' ELSE 'Gone' END AS Flag
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

使用lag()lead():

select t.*,
       (case when prev_date < add_months(date, -1) or
                  prev_date is null
             then 'new'
             when next_date > add_months(date, 1) or
                  next_date is null
             then 'gone'
        end) as flag
from (select t.*,
             lag(date) over (partition by owner, store order by date) as prev_date,
             lead(date) over (partition by owner, store order by date) as lead_date
      from t
     ) t;