SQL - 检查项目在上个月是不是可用,然后标记它
Posted
技术标签:
【中文标题】SQL - 检查项目在上个月是不是可用,然后标记它【英文标题】:SQL - Check if an item was available in the previous month and then flag itSQL - 检查项目在上个月是否可用,然后标记它 【发布时间】:2019-12-20 00:19:33 【问题描述】:我正在尝试解决 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
这是一个显示所有者及其商店信息的表格。所有者可以在一个月内拥有一家商店,但该商店可能会在下个月消失。或者,他们的商店可能在一月份出现,但在二月份就消失了。
我想找到一种方法来标记这个商店移动,所以如果一个商店在一月份存在,二月份就消失了,我会将一个列标记为“消失”。如果一家商店在一月份没有出现,但在二月份出现了,我会将其标记为“新”。
谁能帮我解决这个问题?谢谢!
【问题讨论】:
只需创建一个subquery
以匹配上个月的数据
【参考方案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;
【讨论】:
【参考方案2】: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
【讨论】:
嘿 Mohammad,谢谢,您的解决方案确实有效,但我只收到已消失商店的标记。我怎样才能获得新商店的旗帜?这在前几个月不存在。 @Renato 你想让我更新我的答案还是你已经得到了答案? :) @Renato 我更新了我的答案,请检查小提琴,如果它满足您的需求,我将不胜感激或接受我的答案【参考方案3】:SELECT
ID,
OWNER,
STORE,
DATE,
CASE WHEN DATE IN (SELECT DATE FROM TableName
WHERE DATE IN (<InsertDatesHere)) THEN 'NEW' ELSE 'Gone' END AS Flag
【讨论】:
请注意,我只是作为习惯添加了 ID 列。对我来说,所有表都应该有一个唯一的 ID 列。以上是关于SQL - 检查项目在上个月是不是可用,然后标记它的主要内容,如果未能解决你的问题,请参考以下文章