简体   繁体   English

SQL 服务器 CTE 中基于日期的其他 ID 的总和

[英]Sum of other ID's based on date in SQL Server CTE

My sample CTE which is coming from multiple sources and drawing data from:我的样本 CTE 来自多个来源并从以下位置提取数据:

with sample_cte as 
(
    ae.spvr as col1,
    ae.startDate as start_dt,
    ae.END_DT as end_dt,
    round(ae.Scre, 2, 1) as Scre,
from 
    diff_sources ae

I have a CTE which produces me an output like below:我有一个 CTE,它产生了一个 output,如下所示:

col1 | start_dt | end_dt | score
-----+----------+--------+-------
a    | 10-01-19 |10-02-19| 50.50
a    | 10-02-19 |10-03-19| 55.50
b    | 10-01-19 |10-02-19| 60.50
b    | 10-02-19 |10-03-19| 65.50
c    | 10-01-19 |10-02-19| 70.50
c    | 10-02-19 |10-03-19| 75.50

I am looking for to add new column which gets the sum of scores based on their dates (sum of scores b and c for a, similarly sum of a and b for c).我正在寻找添加新列,该列根据日期获得分数总和(a 的分数总和 b 和 c,c 的 a 和 b 的总和类似)。

The way it looks is something like below它的外观如下所示

col1 | start_dt | end_dt | new_sum_score_column
-----+----------+--------+----------------------------------------------
a    | 10-01-19 |10-02-19| sum of b and c on these dates = (60.50+70.50)
a    | 10-02-19 |10-03-19| sum of b and c on these dates = (65.50+75.50)
b    | 10-01-19 |10-02-19| sum of a and c on these dates = (50.50+70.50)
b    | 10-02-19 |10-03-19| sum of a and c on these dates = (55.50+75.50)
c    | 10-01-19 |10-02-19| similar logic
c    | 10-02-19 |10-03-19| 

Assuming the date reference is to the first column, I think this works:假设日期参考是第一列,我认为这有效:

select t.*,
       sum(score) over (partition by start_dt) - score
from t;

That is.那是。 . . . . calculate the overall sum and subtract the current value.计算总和并减去当前值。

EDIT:编辑:

If there are multiple startdates, then:如果有多个开始日期,则:

select t.*,
       (sum(score) over (partition by start_dt) - 
        sum(score) over (partition by start_dt, col1)
       )
from t;

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

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