SQL Server>如何从日志中查询总和

时间:2013-05-22 14:06:17

标签: sql sql-server

下表包含三个用户随时间的状态变化。 我正在尝试创建一个返回所有用户状态总和的查询,但仅限于今天最近的行

idEvent | date | user    | state
5       | 05/22 | client1 | 0 <- This number
4       | 05/22 | client2 | 1 <- Plus this number
3       | 05/12 | client1 | 0
2       | 05/12 | client2 | 0
1       | 05/02 | client3 | 1
使用此数据,当前客户端最近状态的总和为1(client1最近状态= 0,client2最近状态= 1)。

到目前为止,我已经来了 SELECT sum(a.states) FROM
(SELECT sum(state) AS states
FROM TABLE
WHERE day(date) = day(getdate()) AND month(date) = month(getdate()) AND year(date) = year(getdate())
group by user) a

但它总结了当天的每一个状态,而不是最近的......

任何人都可以帮助我吗? 干杯:)

2 个答案:

答案 0 :(得分:1)

一种方法是使用row_number()查找最近的行,如:

select sum(t.states)
from (select t.*,
             row_number() over (partition by [user] order by [date] desc, idevent desc) as seqnum
      from [table] t
     ) t
where seqnum = 1;

这并不能保证它们来自今天。为此,需要where子句:

select sum(t.states)
from (select t.*,
             row_number() over (partition by [user] order by [date] desc, idevent desc) as seqnum
      from [table] t
      where [date] >= cast(getdate() as date) and [date] < cast(getdate() + 1 as date)
     ) t
where seqnum = 1;

where子句不使用日期列上的任何函数,因此可以使用适当的索引(如果可用)。

答案 1 :(得分:0)

使用ROW_NUMBER和PARTITION BY ...

SELECT sum(STATE)FROM ( SELECT *,ROW_NUMBER()OVER([USER] ORDER BY [DATE] DESC的分区)作为行号 来自#TEMP )T 在哪里ROWNUMBER = 1