Ron*_*ijm 7 sql t-sql recursion
可能重复:
如何在不使用游标的情况下计算SQL中的运行总计?
这有点难以解释,所以我将通过一个例子展示我想要的东西:
可以说我们有以下表格命名MonthProfit
:
[MonthId][Profit]
1, 10 -- January
2, 20 -- February
3, 30
4, 40
5, 50
6, 60
7, 70
8, 80
9, 90
10, 100
11, 110
12, 120 -- December
Run Code Online (Sandbox Code Playgroud)
列profit
表示该月的利润.
但是,如果我们1月份有10个利润,2月份有20个,那么2月份我们的利润总额为30.
所以我想创建一个显示以下内容的视图:
[MonthId][Profit][ProfitTotal]
1, 10, 10 -- January
2, 20, 30 -- February
3, 30, 60
4, 40, 100
5, 50, 150
6, 60, 210
7, 70, 280
8, 80, 360
9, 90, 450
10, 100, 550
11, 110, 660
12, 120, 780 -- December
Run Code Online (Sandbox Code Playgroud)
我现在要解决的问题是这样的观点:
SELECT [MonthId]
,[Profit]
, (SELECT SUM([Profit])
FROM MonthProfit
WHERE [MonthId] <= outer.[MonthId]) as ProfitTotal
FROM MonthProfit as outer
Run Code Online (Sandbox Code Playgroud)
但是,我认为这很慢,因为它必须一直重新计算所有内容,而且对我来说似乎并不优雅.这样做有"好"的方法吗?
我在这里尝试了一个小例子供您参考,这会根据要求生成结果
CREATE TABLE [dbo].[tbl_TotalPrevious](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[values] [bigint] NOT NULL)
Run Code Online (Sandbox Code Playgroud)
将数据插入表中
insert into tbl_TotalPrevious values ('A', 10)
insert into tbl_TotalPrevious values ('B', 20)
insert into tbl_TotalPrevious values ('C', 10)
insert into tbl_TotalPrevious values ('D', 10)
insert into tbl_TotalPrevious values ('E', 10)
insert into tbl_TotalPrevious values ('F', 10)
insert into tbl_TotalPrevious values ('G', 10)
insert into tbl_TotalPrevious values ('H', 10)
insert into tbl_TotalPrevious values ('I', 10)
insert into tbl_TotalPrevious values ('J', 10)
insert into tbl_TotalPrevious values ('K', 10)
insert into tbl_TotalPrevious values ('L', 10)
insert into tbl_TotalPrevious values ('M', 10)
insert into tbl_TotalPrevious values ('N', 10)
insert into tbl_TotalPrevious values ('O', 10)
insert into tbl_TotalPrevious values ('P', 10)
insert into tbl_TotalPrevious values ('Q', 10)
insert into tbl_TotalPrevious values ('R', 10)
insert into tbl_TotalPrevious values ('S', 10)
insert into tbl_TotalPrevious values ('T', 10)
insert into tbl_TotalPrevious values ('U', 10)
insert into tbl_TotalPrevious values ('V', 10)
insert into tbl_TotalPrevious values ('W', 10)
insert into tbl_TotalPrevious values ('X', 10)
insert into tbl_TotalPrevious values ('Y', 10)
Run Code Online (Sandbox Code Playgroud)
创建一个函数,例如。
ALTER FUNCTION testtotal
(
@id int
)
RETURNS int
AS
BEGIN
DECLARE @Result int
SELECT @Result = (SELECT SUM([values])
FROM tbl_TotalPrevious
WHERE [id] <= @id)
RETURN @Result
END
GO
Run Code Online (Sandbox Code Playgroud)
单个查询生成的结果
SELECT [id],[values], (dbo.testtotal(id)) as TotalVals FROM tbl_TotalPrevious
Run Code Online (Sandbox Code Playgroud)
希望上述内容能够解决您的时间问题,并根据需要更快地生成数据。
归档时间: |
|
查看次数: |
1733 次 |
最近记录: |