【问题标题】:Compare ID's (new, existing, dropped) over time随着时间的推移比较 ID(新的、现有的、删除的)
【发布时间】:2018-07-27 14:50:23
【问题描述】:

非常感谢您的专业知识。这是我的问题,我们有一个包含 ID 和快照日期的月度快照表:

ID,Snapshot_Date 1,Dec-17 2、12月17日 3,Dec-17 1,1月18日 3,1月18日 4,1月18日 3、2月-18日 5、2-18 6、2-18

要求能够在任何给定月份(通常是最近的月份)报告我们从 [某个月份和年份] 开始使用 x 个 ID、丢失 Y 个 ID 并获得 Z 个 ID。

SQL 查询的一个逻辑是返回所有月份、所有 ID 及其状态,0=结转,+1=新,-1=已删除。请注意 ID=2 是如何从 2 月 18 日删除的,因为我们注意到它在 1 月 18 日的结果中下降了:

Snapshot_Date、ID、状态 12 月 17 日,1,+1 12 月 17 日,2,+1 12 月 17 日,3,+1 Jan-18,1,0 Jan-18,2,-1 Jan-18,3,0 1 月 18 日,4,+1 2月18,1,-1 2月-18,3,0 2月-18,4,0 2 月 18 日,5,+1

【问题讨论】:

  • 你怎么知道id 1 在一月份下降了?我只看到创造的记录。
  • 每个月都是一个快照,所以 id 1 是在 12 月创建的,并且也包含在 1 月的快照中,所以它被结转了。抱歉,问题的格式不正确。

标签: sql amazon-redshift


【解决方案1】:

为回答此类问题而必须构建的数据模型基于 ID 和时间单位的所有可能组合,即您需要在每个月为您的案例中的每个 ID 创建一个记录,并说明该 ID 是否本月是否存在,与上个月相同。概念证明如下所示:

WITH
 ids as (
    select distinct id from your_table
)
,months as (
    select distinct snapshot_date from your_table
)
,id_month_pairs as (
    select *
    from ids
    cross join months
)
,id_months as (
    select *
    ,(your_table.id is not null) as is_present_this_month
    ,lag(your_table.id is not null) over (partition by id order by to_date(snapshot_date,'Mon-YY')) as is_present_prev_month
    from id_month_pairs
    left join your_table
    using (id, snapshot_date)
)
select 
 snapshot_date as month
,sum(case when is_present_this_month and is_present_prev_month then 1 else 0 end) as carried_over
,sum(case when is_present_this_month and not is_present_prev_month then 1 else 0 end) as gained
,sum(case when not is_present_this_month and is_present_prev_month then 1 else 0 end) as lost
from id_months
group by 1
order by to_date(snapshot_date,'Mon-YY')

实际上,您可以做的是在新表中具体化id_months 步骤(在 Redshift 中执行 ELT),将文本月份转换为日期月份并添加其他有用的维度,然后针对该表单独运行聚合步骤。

附:选择 distinct 和 cross join 来获得 id_months 不是最优的,这只是为了展示一般想法。您可以拥有月份日期表并将其加入 ID 列表,以便记录仅从 ID 存在的第一个月开始,而不是所有月份/ID 对。但我把这个留给你:)

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2016-04-25
    相关资源
    最近更新 更多