请帮我在SQL Server中编写此查询

时间:2013-09-12 05:21:54

标签: sql sql-server

考虑下表:

 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

3 个答案:

答案 0 :(得分:5)

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

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

An SQLfiddle to test with

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

答案 1 :(得分:2)

如果你使用sql Server 2012,你可以试试这个。

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

Sql Fiddle Demo

答案 2 :(得分: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]