SQL如何取得比当前行日期小的所有行的数量加总
请问如何用静态SQL实现查询,取得比当前行日期小的所有行的数量加总,如下
tbl
时间,数量
10/1 1
10/2 2
10/3 3
10/4 2
如何得到
时间,数量,加总
10/1 1 0(没有比10/1小的日期,所以为0)
10/2 2 1(比该行日期10/2小的只有10/1的数量1)
10/3 3 3(比该行日期10/3小的有10/1的数量1和10/2的数量2)
10/4 2 5(比该行日期10/4小的有10/1的数量1和10/2的数量2和10/3的数量3)
[解决办法]
CREATE TABLE tb(dt DATETIME,num int)
INSERT INTO [dbo].[tb] ([dt],[num]) VALUES ('2013-10-1',1)
INSERT INTO [dbo].[tb] ([dt],[num]) VALUES ('2013-10-2',2)
INSERT INTO [dbo].[tb] ([dt],[num]) VALUES ('2013-10-3',3)
INSERT INTO [dbo].[tb] ([dt],[num]) VALUES ('2013-10-4',2)
GO
SELECT * FROM [tb] t
CROSS APPLY (
SELECT SUM(t2.num) ct FROM tb t2 WHERE t2.dt<t.dt
) r
GO
--result
dt num ct
----------------------- ----------- -----------
2013-10-01 00:00:00.000 1 NULL
2013-10-02 00:00:00.000 2 1
2013-10-03 00:00:00.000 3 3
2013-10-04 00:00:00.000 2 6
(4 行受影响)
WITH a1 ([时间],[数量]) AS
(
SELECT '10/1', 1 UNION ALL
SELECT '10/2', 2 UNION ALL
SELECT '10/3', 3 UNION ALL
SELECT '10/4', 2
)
SELECT [时间],[数量],ISNULL((SELECT SUM([数量]) FROM a1 WHERE [时间]<a.[时间]),0) [加总]
FROM a1 a
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-10 17:31:28
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[tbl]
if object_id('[tbl]') is not null drop table [tbl]
go
create table [tbl]([时间] varchar(4),[数量] int)
insert [tbl]
select '10/1',1 union all
select '10/2',2 union all
select '10/3',3 union all
select '10/4',2
--------------开始查询--------------------------
select * ,ISNULL((SELECT SUM([数量]) FROM tbl a WHERE a.[时间]<tbl.[时间]),0)加总
from [tbl]
----------------结果----------------------------
/*
时间 数量 加总
---- ----------- -----------
10/1 1 0
10/2 2 1
10/3 3 3
10/4 2 6
*/