使用SUM运行总计的T-SQL

时间:2012-08-16 06:45:19

标签: sql sql-server-2008 tsql

我有一个简单的表,其中包含一些虚拟数据设置:

|id|user|value|
---------------
 1  John   2
 2  Ted    1
 3  John   4
 4  Ted    2

我可以通过执行以下sql(MSSQL 2008)语句来选择运行总计:

SELECT a.id, a.user, a.value, SUM(b.value) AS total
FROM table a INNER JOIN table b
ON a.id >= b.id
AND a.user = b.user
GROUP BY a.id, a.user, a.value
ORDER BY a.id

这会给我一些结果:

|id|user|value|total|
---------------------
 1  John   2     2
 3  John   4     6
 2  Ted    1     1
 4  Ted    2     3

现在是否可以只检索每个用户的最新行?结果将是:

|id|user|value|total|
---------------------
 3  John   4     6
 4  Ted    2     3

我是以正确的方式来做这件事的吗?任何建议或新的路径都会很棒!

5 个答案:

答案 0 :(得分:9)

不需要加入,您可以通过这种方式加快查询速度:

select id, [user], value, total
from
(
  select id, [user], value, 
  row_number() over (partition by [user] order by id desc) rn, 
  sum(value) over (partition by [user]) total
from users
) a
where rn = 1

答案 1 :(得分:5)

试试这个:

;with cte as 
     (SELECT a.id, a.[user], a.value, SUM(b.value) AS total
    FROM users a INNER JOIN users b
    ON a.id >= b.id
    AND a.[user] = b.[user]
    GROUP BY a.id, a.[user], a.value
     ),
cte1 as (select *,ROW_NUMBER() over (partition by [user] 
                         order by total desc) as row_num
         from cte)
select  id,[user],value,total from cte1 where row_num=1

SQL Fiddle Demo

答案 2 :(得分:1)

添加where语句:

select * from
(
your select statement
) t

where t.id in (select max(id) from table group by user)

您也可以使用此查询:

SELECT a.id, a.user, a.value, 

(select max(b.value) from table b where b.user=a.user) AS total

FROM table a 

where a.id in (select max(id) from table group by user)

ORDER BY a.id

答案 3 :(得分:0)

添加右连接比嵌套选择更好。

甚至更简单:

SELECT MAX(id), [user], MAX(value), SUM(value)
FROM table
GROUP BY [user]

答案 4 :(得分:0)

与SQL Server 2008或更高版本兼容

DECLARE @AnotherTbl TABLE
    (
        id           INT
      , somedate     DATE
      , somevalue    DECIMAL(18, 4)
      , runningtotal DECIMAL(18, 4)
    )

INSERT INTO @AnotherTbl
    (
        id
      , somedate
      , somevalue
      , runningtotal
    )
SELECT  LEDGER_ID
      , LL.LEDGER_DocDate
      , LL.LEDGER_Amount
      , NULL
FROM    ACC_Ledger LL
ORDER BY LL.LEDGER_DocDate

DECLARE @RunningTotal DECIMAL(18, 4)
SET @RunningTotal = 0

UPDATE  @AnotherTbl
SET @RunningTotal=runningtotal = @RunningTotal + somevalue
FROM    @AnotherTbl

SELECT  *
FROM    @AnotherTbl