繁体   English   中英

需要获取与最近列值关联的 id

[英]Need to get an id associated with the most recent column value

SQL 查询

select id, month_id, id_type,
      max(case when immediate_prev <> id_type then immediate_prev
              end) over (partition by id, id_type, (seqnum - seqnum_2)
              ) as id_type_prev
from (select *,
            row_number() over (partition by id order by month_id) as seqnum,
            row_number() over (partition by id, id_type order by month_id) as seqnum_2,
            lag(id_type) over (partition by id order by month_id) as immediate_prev
      from `my_table`
      WHERE id = 123
        )
ORDER BY month_id asc

my_table数据

id|month_id|id_type
123|202001|aaa
123|202002|aaa
123|202003|aaa
123|202004|bbb
123|202005|bbb
123|202006|bbb

查询返回数据

id|month_id|id_type|id_type_prev
123|202001|aaa|null
123|202002|aaa|null
123|202003|aaa|null
123|202004|bbb|aaa
123|202005|bbb|aaa
123|202006|bbb|aaa

我有一个 SQL 查询,它返回给定 id 的前一个id_type值。 我也想知道前一个month_idid_type ,但我不知道如何获取这些信息。 以上是表数据和我当前查询返回的内容。

下面是我所追求的附加数据,我希望能帮助我将month_id_prev添加到我的上述查询中。 这将是前一个id_type最近的 month_id。

id|month_id|id_type|id_type_prev|month_id_prev
123|202001|aaa|null|null
123|202002|aaa|null|null
123|202003|aaa|null|null
123|202004|bbb|aaa|202003
123|202005|bbb|aaa|202003
123|202006|bbb|aaa|202003

使用您的示例数据考虑以下方法:

with sample_data as (
  select 123 as id, 202001 as month_id, 'aaa' as id_type,
  union all select 123 as id, 202002 as month_id, 'aaa' as id_type,
  union all select 123 as id, 202003 as month_id, 'aaa' as id_type,
  union all select 123 as id, 202004 as month_id, 'bbb' as id_type,
  union all select 123 as id, 202005 as month_id, 'bbb' as id_type,
  union all select 123 as id, 202006 as month_id, 'bbb' as id_type,
),
cte1 as (
select id, month_id, id_type,
      max(case when immediate_prev <> id_type then immediate_prev
              end) over (partition by id, id_type, (seqnum - seqnum_2)
              ) as id_type_prev,
      latest_ym,
      lag(latest_ym) over (partition by id order by month_id) as prev_ym
from
(select *,
        row_number() over (partition by id order by month_id) as seqnum,
        row_number() over (partition by id, id_type order by month_id) as seqnum_2,
        lag(id_type) over (partition by id order by month_id) as immediate_prev,
        last_value(month_id) over (partition by id,id_type order by id) as latest_ym
from sample_data)

)

select 
  id,
  month_id,
  id_type,
  id_type_prev,
  max(if(month_id > prev_ym, prev_ym, null)) over (partition by id,id_type) as month_id_prev
from cte1
order by month_id asc

Output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM