我有一个表,其中包含一个person_ID,一个日期以及一个用于指示该人是否在该日期完成任务的指示器,例如:
Person ID Date Status
0001 2018-01-01 Success
0001 2018-01-05 Failure
0001 2018-01-09 Success
0001 2018-01-10 Success
0002 2018-01-01 Success
0002 2018-01-03 Success
0003 2018-01-01 Failure
0003 2018-01-02 Failure
0003 2018-01-04 Success
我想获得每个人在每个日期迄今成功的次数和迄今为止经历的失败次数的计数:
Person ID Date Running Running
# Successes # Failures
0001 2018-01-01 1 0
0001 2018-01-05 1 1
0001 2018-01-09 2 1
0001 2018-01-10 3 1
0002 2018-01-01 1 0
0002 2018-01-03 2 0
0003 2018-01-01 0 1
0003 2018-01-02 0 2
0003 2018-01-04 1 2
我真的不知道从哪里开始编写查询来做到这一点-如何使用T SQL做到这一点?感谢帮助!
答案 0 :(得分:2)
您可以使用累计金额;
select t.*,
sum(case when status = 'success' then 1 else 0 end) over (partition by person_id order by date) as running_success,
sum(case when status = 'failure' then 1 else 0 end) over (partition by person_id order by date) as running_failure
from t;