[英]SQL - Check if an item was available in the previous month and then flag it
I'm trying to solve a problem in SQL but without much success so far.我正在尝试解决 SQL 中的问题,但到目前为止还没有取得多大成功。 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.
或者,他们的商店可能在 1 月出现,但在 2 月消失。
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!
谢谢!
Use lag()
and lead()
:使用
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;
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.