我正在尝试解决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
这是一个表,显示有关所有者及其商店的信息。所有者可以在一个月内拥有一家商店,但是该商店可能在下个月消失。或者,他们的商店可能在一月开张,但二月就消失了。
我想找到一种方法来标记此商店的移动,因此,如果一月有一家商店,而二月又去了,我会标记一个列为“已消失”。如果一家商店在一月不存在,而是在二月出现,我将其标记为“新”。
有人可以帮我吗?谢谢!
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
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;