5

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

|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

我会以正确的方式解决这个问题吗?任何建议或遵循的新路径都会很棒!

4

5 回答 5

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
于 2012-08-16T08:51:24.220 回答
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 小提琴演示

于 2012-08-16T07:19:24.350 回答
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
于 2012-08-16T06:49:19.320 回答
0

添加右连接会比嵌套选择执行得更好。

或者更简单:

SELECT MAX(id), [user], MAX(value), SUM(value)
FROM table
GROUP BY [user]
于 2012-08-16T06:55:55.343 回答
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
于 2016-11-14T14:22:03.890 回答