【问题标题】:Looking for a query to differentiate record based on month/year查找查询以根据月/年区分记录
【发布时间】:2021-02-08 05:23:12
【问题描述】:

我有下表:

month year first_seen last_seen ent1 ent2
1 2020 2020-01-02 2020-01-02 223035722222 44414152023333
2 2020 2020-03-02 2021-03-02 223035744444 44414152022009
1 2021 2021-01-02 2021-01-02 223035744444 44414152022009
1 2021 2021-01-02 2021-01-02 223035743333 44414152021008
2 2021 2021-02-02 2021-02-02 223035743333 44414152021008
2 2021 2021-02-02 2021-02-08 542232323323 55524334455433
2 2021 2021-02-05 2021-02-09 343223344555 44343434343444

现在我想跳过那些具有相同 first_seenlast_seen 并且只有一个条目的条目,即如果一个条目具有相同的 first_seen > 和 last_seen,但在两个不同的月份或年份,则不会跳过该条目。

例如从上表中,我想要以下结果:

month year first_seen last_seen ent1 ent2
2 2020 2020-03-02 2021-03-02 223035744444 44414152022009
1 2021 2021-01-02 2021-01-02 223035744444 44414152022009
1 2021 2021-01-02 2021-01-02 223035743333 44414152021008
2 2021 2021-02-02 2021-02-02 223035743333 44414152021008
2 2021 2021-02-02 2021-02-08 542232323323 55524334455433
2 2021 2021-02-05 2021-02-09 343223344555 44343434343444

在上面的结果表中,只有第一行被跳过,因为它具有相同的 first_seenlast_seen 并且只出现一次。虽然 table 1row 2 & row 3 条件相同但出现了不止一次(不同年份)和 row 4 第 5 行 也有相同的条件,但出现在不同的月份。

【问题讨论】:

  • 该表有数百万个条目,按月和年进行分区
  • 第 4 行和第 5 行不满足 first_seen = last_seen 那么为什么会出现在预期结果中?
  • 这两行的 first_seen != last_seen 所以它们应该出现,只有那些不应该出现的行具有条件 first_seen = last_seen
  • 只有 table 1 的第一行被跳过,因为它有 first_seen = last_seen 并且只有一个条目,即在任何其他月份或年份都没有出现
  • 我们也在查看 ent1ent2 列以过滤结果,但稍后会出现。

标签: sql postgresql data-analysis


【解决方案1】:

首先我确定了 ent1 和 ent2 的行数,然后我只选择了那些 count>1 或 first_seenlast_seen 的行。请查看:

with Results as (
select * ,count(*) over(partition by ent1,ent2  rows between unbounded preceding and unbounded following) Row_Count
from S66096277 
)
select  month,year,first_seen,last_seen,ent1,ent2 
from results 
where Row_Count>=2 or first_seen<>last_seen;

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多