如果带有时间戳大查询

IF with timestamp bigquery

我需要添加一个属性来指示该版本是原始版本还是副本。如果是本站第一版,就是原创,否则,就是复制。

table:

id_site  id_version timestamp_version
1        5589       2/3/2022
1        2030       10/7/2022
1        1560       10/8/2022
2        6748       2/3/2022
2        7890       2/4/2022
3        4532       2/3/2022

预期结果:

id_site id_version  timestamp_version   type_version
1       5589        2/3/2022            original
1       2030        10/7/2022           copy
1       1560        10/8/2022           copy
2       6748        2/3/2022            original
2       7890        2/4/2022            copy
3       4532        2/3/2022            original

您可以在 if 语句中使用 window 函数:

with test as (

    select * from unnest([
        struct(1 as id_site, 5589 as id_version, timestamp(date "2022-03-02") as timestamp_version),               
            (1, 2030, timestamp(date "2022-07-10")),
            (1, 1560, timestamp(date "2022-08-10")),
            (2, 6748, timestamp(date "2022-03-02")),
            (2, 7890, timestamp(date "2022-04-02")),
            (3, 4532, timestamp(date "2022-03-02"))
    ])
)

select 
    *,
    IF(timestamp_version = min(timestamp_version) over (partition by id_site), "original", "copy") AS type_version 
from test

您可以在此处使用 IFCASE。它们大多可以互换,但我更喜欢 CASE,因为它可以移植到几乎任何其他 RDBMS,其中 IF 仅在少数情况下得到支持。

 CASE WHEN ROW_NUMBER() OVER (PARTITION BY id_site ORDER BY timestamp_version ASC) = 1 THEN 'copy' ELSE 'original' END

CASE 表达式中,我们执行 ROW_NUMBER() window 函数将“window”或按 [=16= 对结果集中的每一行进行分区] 并为每个不同 id_site 的每个记录编号,按 timestamp_version 升序排列。我们测试一下 ROW_NUMBER() 是否是 1 然后用 originalcopy.

标记它

考虑以下选项

select *,
  if(lag(id_version) over prev is null, 'original', 'copy') type_version,
from your_table
window prev as (partition by id_site order by timestamp_version)    

如果应用于您问题中的示例数据 - 输出为