0

考虑这张表:

 dt           qnt 
----------   -------
1               10
2               -2
3               -4
4                3
5               -1
6                5

如何创建查询以获取此结果?(res 是一个运行总计列):

 dt       qnt       res
----     -----     -----
1         10         10
2         -2          8
3         -4          4
4          3          7
5         -1          6
6          5          11
4

3 回答 3

5

您可以使用一个简单的子查询来计算当前行的总和,这应该适用于任何版本的 SQL Server;

SELECT dt, qnt, 
  (SELECT SUM(qnt) FROM Table1 ts WHERE ts.dt <= t1.dt) res
FROM Table1 t1
ORDER BY dt;

一个用于测试的 SQLfiddle

如果您使用的是 SQL Server 2012,请参阅Amit 的答案以获得更有效的查询。

于 2013-09-12T05:26:15.380 回答
2

如果您使用的是 sql Server 2012,则可以这样尝试。

Select * ,Sum([qnt]) Over(order by dt) from table1

Sql 小提琴演示

于 2013-09-12T05:28:44.583 回答
2

使用其中一种方式:

    CREATE TABLE [dbo].[T1]
        (
          [dt] [int] IDENTITY(1, 1)
                     NOT NULL ,
          qnt  [int] NULL ,
          CONSTRAINT [PK_T1] PRIMARY KEY CLUSTERED ( [dt] ASC )
            WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                   IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                   ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
        )
    ON  [PRIMARY]
    GO

    INSERT  INTO dbo.T1 ( qnt ) VALUES  ( 10 )
    INSERT  INTO dbo.T1 ( qnt ) VALUES  ( -2 )
    INSERT  INTO dbo.T1 ( qnt ) VALUES  ( -4 )
    INSERT  INTO dbo.T1 ( qnt ) VALUES  ( 3 )
    INSERT  INTO dbo.T1 ( qnt ) VALUES  ( -1 )
    INSERT  INTO dbo.T1 ( qnt ) VALUES  ( 5 )
    GO

    SELECT  * ,
            RunningSum = T1.qnt + COALESCE(( SELECT   SUM(qnt)
                                               FROM     T1 AS T1Sub
                                               WHERE    ( T1Sub.dt < T1.dt )
                                             ), 0)
    FROM    T1

    Go

    SELECT  T1.dt ,
            T1.qnt ,
            SUM(T1Inner.qnt)
    FROM    T1
            INNER JOIN T1 AS T1Inner ON ( T1.dt >= T1Inner.dt )
    GROUP BY T1.dt ,
            T1.qnt
    ORDER BY T1.dt ,
            T1.qnt

    GO

    SELECT  T1.* ,
            T2.RunningSum
    FROM    T1
            CROSS APPLY ( SELECT    SUM(qnt) AS RunningSum
                          FROM      T1 AS CAT1
                          WHERE     ( CAT1.dt <= T1.dt )
                        ) AS T2

    Go

    SELECT  * ,
            RunningSum = ( SELECT   SUM(qnt)
                           FROM     T1 AS T1In
                           WHERE    ( T1In.dt <= T1.dt )
                         )
    FROM    T1  

    Go


    -- In Sql Server 2012
    SELECT  * ,
            SUM(T1.qnt) OVER ( ORDER BY T1.dt 
                               ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )
                               AS RunningTotal
    FROM    T1



    Drop Table [dbo].[T1]
于 2014-11-22T23:08:08.890 回答