sql - 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
解决方案
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
推荐阅读
- r - 将重复项作为一个循环。
- javascript - 3到5个api接口是什么意思?
- c++ - 当我将 uint8_t * 转换为整数时会发生什么?
- css - html输入\文本区域的默认最大长度是多少?
- android - Firebase 身份验证返回 400
- python - 检查目标时出错:预期 activation_2 的形状为 (512,),但数组的形状为 (1,)
- events - Eloquent 5.7:创建事件
- unit-testing - 如何在 VS Code 中交互式调试 NodeJS 测试套件?
- angular - 基于 Angular 6 中的守卫路由到其他页面,rxjx 6 异步请求
- ruby-on-rails - 在 Rails.application.routes.draw Rails 5.2 中使用引擎路由