首页 > 解决方案 > SQL 可行性:可以按值挤出行并以自定义方式组合表吗?

问题描述

假设我有以下 sql 表:

// foo

// columns 
ID 
DATE
SIZE
LIFETIME

其中foo表示对象从驱动器中删除时的大小和日期。

假设我有第二张桌子,

// bar
ID
DATE
SIZE

其中 bar 只是一个表格,对于特定对象在驱动器上的每一天(并且此处的覆盖范围可能不完整),仅包含有关该对象当天大小的信息。


现在,我在 SQL 查询之外执行以下操作,这非常耗时:对于 foo 中的每个 ID,将最后一个已知大小挤出到“LIFETIME”行中(其中 1 行在生命周期 N 中变为 N 行,最后已知大小)。

然后,我使用表中的信息更新每个时间步的大小值bar,每个 ID,当它可用于特定时间步时。


可以在 SQL 查询中执行此计算吗?换句话说:调查会不会浪费时间?



通过手动示例,为简单起见,使用整数而不是天数:

// foo initial
ID DATE SIZE LIFETIME
a,1000,20.5,2
b,500,40.8,4

// foo after "extrusion" with last known size value
ID DATE SIZE LIFETIME
a,1000,20.5,2
a,999,20.5,1
a,998,20.5,0
b,500,40.8,4
b,499,40.8,3
b,498,40.8,2
b,497,40.8,1
b,496,40.8,0


// bar initial
ID DATE SIZE
a,998,2.0
b,499,34.0
b,498,30.0
b,496,10.0

最后,foobar数据:

// foobar combined
ID DATE SIZE LIFETIME
a,1000,20.5,2
a,999,20.5,1
a,998,2.0,0
b,500,40.8,4
b,499,34.0,3
b,498,30.0,2
b,497,40.8,1 // if this could have the least neighboring size value with id b
b,496,10.0,0 // that would be amazing, but thought this would be a good start

// defining least neighboring size value: 
//    Given
c,26,72 // obj c @ time 35 with size 72
c,23,35 // obj c @ time 23 with size 35

// then the extrusion would be:
c,26,72,j
c,25,35,j-1
c,24,35,j-2
c,23,35,j-3

标签: sqlsnowflake-cloud-data-platform

解决方案


with numbers as (select n from ...), /* values from 1 to max necessary */
select *
from foo f inner join numbers z on z.n <= f.lifetime
    cross apply (
        select top 1 size from bar b
        where b.id = f.id and f.date <= z.n
        order by z.n desc
    ) s

推荐阅读