日期:2014-05-17 浏览次数:20489 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-04-15 10:40:17
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([foreignkey] varchar(11),[monthmoney] int,[totalmoney] int)
insert [huang]
select 'asdfasdf',2,3 union all
select 'asdzxcvdrwe',1,2 union all
select 'we23r2fds',12,9
--------------开始查询--------------------------
;WITH cte AS (SELECT *,ROW_NUMBER()OVER(ORDER BY GETDATE())id FROM huang )
select foreignkey,(SELECT SUM(monthmoney) FROM cte a WHERE a.id<=cte.id ),(SELECT SUM([totalmoney]) FROM cte a WHERE a.id<=cte.id )
from cte
----------------结果----------------------------
/*
foreignkey
----------- ----------- -----------
asdfasdf 2 3
asdzxcvdrwe 3 5
we23r2fds 15 14
*/