每天计算不同的值,不包括重新更新直到值更改

时间:2014-10-21 11:15:53

标签: sql sql-server sql-server-2008 distinct

我真的在努力解释如何解释这一点,所以我会尝试给你下面表格的格式和期望的结果。

我有一个包含uniqueID,date,userID和result的表。我正在尝试计算每天“正确”的结果数,但我只想根据userID列计算唯一的出现次数。然后,我想要排除任何特定用户标识的'正确'的出现,直到userID的结果变为'成功'。

UID Date        UserID Result
1   01/01/2014  5    Correct
2   01/01/2014  5    Correct
3   02/01/2014  4    Correct
4   03/01/2014  4    Correct
5   03/01/2014  5    Incorrect
6   03/01/2014  4    Incorrect
7   05/01/2014  5    Correct
8   07/01/2014  4    Correct
9   08/01/2014  5    Success
10  08/01/2014  4    Success

根据以上数据,我希望看到以下内容:

Date        Correct Success
01/01/2014  1       0
02/01/2014  1       0
03/01/2014  0       0
05/01/2014  0       0
07/01/2014  0       0
08/01/2014  0       2

有人可以帮忙吗?我正在使用SQL Server 2008

1 个答案:

答案 0 :(得分:2)

count(distinct)case

一起使用
select date,
       count(distinct case when result = 'Correct' then UserId end) as Correct,
       count(distinct case when result = 'Success' then UserId end) as Success
from data d
group by date
order by date;

编辑:

以上对所有事件都计算correct。如果您只想要计算第一个:

select date,
       count(case when result = 'Correct' and seqnum = 1 then UserId end) as Correct,
       count(case when result = 'Success' and seqnum = 1 then UserId end) as Success
from (select d.*,
             row_number() over (partition by UserId, result order by Uid) as seqnum
      from data d
     ) d;

在这种情况下,distinct是不必要的。

相关问题