我真的在努力解释如何解释这一点,所以我会尝试给你下面表格的格式和期望的结果。
我有一个包含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
答案 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
是不必要的。