使用select语句按前一行编号求和

时间:2019-10-19 17:57:20

标签: sql sql-server tsql

假设有两个列名称SrNo和Salary,我需要第三列,其结果将显示如下:-

import unittest
from urlunshort3 import UrlUnshortener
from urllib.request import Request, urlopen
import urllib.request

def download_file2(download_url):
   print(download_url)
   url = download_url
   response =  urllib.request.urlopen(url)
   data = response.read()
   with open('C:/Users/usuario/Desktop/files/example.pdf', 'wb') as archivo:
       archivo.write(data)
   with open('C:/Users/usuario/Desktop/files/example.pdf', 'r') as archivo:
       print("True")

download_file2(UrlUnshortener().resolve_short("http://bit" + ".ly/31wMeIN"))

因此它将通过将先前的列值添加到当前值来增加,并且应该仅使用select语句而不对其进行任何循环。

2 个答案:

答案 0 :(得分:3)

您正在寻找累计金额。

最简单的方法是:

select t.*, sum(salary) over (order by srno) as running_salary
from t;

使用order by时不需要窗口框架。

答案 1 :(得分:2)

使用新数据集,您可以使用窗口函数和ROWS BETWEEN

SELECT SrNo,
       Salary,
       SUM(Salary) OVER (ORDER BY SrNo
                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Result
FROM YourTable;