-1

我正在尝试解决 SQL 中的一个问题,但到目前为止还没有取得多大成功。我有一张这样的桌子:

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

这是一个表格,显示有关所有者及其商店的信息。所有者可以在一个月内拥有一家商店,但该商店可能会在下个月消失。或者,他们的商店可能在一月份出现,但在二月份就消失了。

我想找到一种方法来标记这个商店运动,所以如果一家商店在一月份存在,二月份就消失了,我会将一个列标记为“消失”。如果一家商店在一月份没有出现,但在二月份出现了,我会将其标记为“新”。

任何人都可以帮助我吗?谢谢!

4

3 回答 3

1

使用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;
于 2019-12-20T01:34:54.917 回答
0
SELECT 
    ID, 
    OWNER, 
    STORE, 
    DATE, 
    CASE WHEN DATE IN (SELECT DATE FROM TableName
WHERE DATE IN (<InsertDatesHere)) THEN 'NEW' ELSE 'Gone' END AS Flag
于 2019-12-20T00:49:12.970 回答
0
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在这里

于 2019-12-20T00:51:06.877 回答