You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在SQL Server中按分组计算累计运行年限的实现方法

在SQL Server中按组件分组计算累计运行年数

原始数据

我在SQL Server中有如下数据:

序号年份Component1Total Run years
12011AAA3
22011BBB5
32011CCC7
42012AAA6
52012BBB2
62012CCC4
72013AAA3
82013BBB2
92013CCC5

需求

需要按年份和Component1分组,计算每个组件从起始年份到当前年份的累计Total Run years,期望结果如下:

年份Component1Total Run years
2011AAA3
2011BBB5
2011CCC7
2012AAA9
2012BBB7
2012CCC11
2013AAA12
2013BBB9
2013CCC16

解决方案

可以使用SQL Server的窗口函数SUM() OVER()实现累计求和,具体SQL语句如下:

SELECT 
    年份,
    Component1,
    SUM([Total Run years]) OVER (PARTITION BY Component1 ORDER BY 年份) AS [Total Run years]
FROM 
    你的表名
ORDER BY 
    年份, Component1;

逻辑说明

  • PARTITION BY Component1:按每个组件单独划分分组,确保累计计算仅针对同一组件的数据
  • ORDER BY 年份:指定按年份升序排序,保证累计值从最早年份到当前年份依次累加
  • 最终结果按年份和Component1排序,与期望结果顺序一致

内容的提问来源于stack exchange,提问作者Mr.RK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:05:44