【问题标题】:SQL Server: inner join running totalSQL Server:内部连接运行总计
【发布时间】:2020-01-10 12:52:39
【问题描述】:

我正在对 SQL Server 2008 数据库(分区之前)做一些工作,并尝试使用内部联接让我的头脑运行总计。我遵循了一些在线教程,但无法获得预期的结果。

这是基础数据...

 Compdate   count
 ------------------
 2          198
 3           29
 4           22
 5           27
 6           31
 9           18
 10          16
 11          22
 12          26
 etc...

我需要添加一个运行总计列。

这是我目前创建的查询...

select 
    t1.Compdate,
    t1.count,
    Sum(t2.count) as 'Total'
from 
    DB_KpiTr_Remo_CumComp_TV t1
inner join 
    (select count, compdate 
     from DB_KpiTr_Remo_CumComp_TV 
     where Month like 'l%') t2 on t1.Count >= t2.Count
                               and t1.Compdate = t2.Compdate
where 
    t1.Month like 'l%'
group by 
    t1.Compdate, t1.count
order by  
    t1.Compdate

select Compdate, count
from DB_KpiTr_Remo_CumComp_TV t1

但我得到的只是我的总列中完全相同的数字......

Compdate    count   Total
-------------------------
2           198     198
3            29      29
4            22      22
etc...

我尝试了几种连接组合,得到了几种结果组合,但没有找到我想要的结果 - 我在这里缺少什么?

【问题讨论】:

  • 左对齐 SQL 很难阅读和编写。

标签: sql tsql sql-server-2008


【解决方案1】:

你可以使用apply:

select u.*, u2.running_count
from underlying u outer apply
     (select sum(u2.count) as running_count
      from underlying u2
      where u2.compdate <= u.compdate
     ) u2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多