找出累积和列中的差距:: SQL Server

时间:2019-04-29 20:20:12

标签: sql-server common-table-expression

我有两个这样的表:

主表:

ID|start|end |Type|Year  
--+-----+----+----+-----
1 |0.00 |3.50|1   |2018  
1 |6.50 |7.25|0   |2018  
2 |10.6 |12.1|1   |2019 

数据表:

ID|start|end |Type|Year|Dir  
--+-----+----+----+----+----
1 |0.00 |1.11|1   |2018|U       
1 |1.88 |3.00|3   |2018|U  
1 |3.00 |3.50|4   |2018|U 
1 |3.00 |3.25|5   |2018|D
1 |3.25 |3.50|5   |2018|D

我正在尝试获取数据表中缺少的开始数据和结束数据。

例如,在“数据”表中,缺少以1.11开头和1.88结尾的行,这就是我想要的样子:

结果表:

ID |start|end |Year  
---+-----+----+----
1  |1.11 |1.88|2018 

到目前为止,我为连接两个表所做的查询是这样的:

select distinct 
    b.id, a.type, a.start, a.end
from 
    dbo.master b 
left outer join 
    data a on a.id = b.id 
           and (a .start + a .end) / 2 >= b.start 
           and (a .start + a .end) / 2 < b.end
where 
    a.type = 0 
group by 
    b.id, b.year

以下查询是要在数据表中完成一些计算:

with cte as
(
    select distinct 
        row_number() over (partition by y.id, y.Year order by y.start) rn,
        y.start, y.end, y.end - y.start length, y.id, y.Year, y.Type 
    from 
        dbo.data y 
    where 
        (y.Type = 1 or y.type = 3 or y.Type = 4) 
    group by 
        y.id, y.year
)
select a.*, Cast(sum(b.length) as float) as cumulative_length
from cte a
join cte b on a.rn >= b.rn
group by a.rn, a.id, a.Year, a.length, a.start, a.ent, a.Type

发现很难与主表建立连接。任何帮助表示赞赏。

0 个答案:

没有答案