我有下表,在这里,我想得到值STAT_NEW ='发送到xxxx项目团队'的计数。在发生值stat_new ='Sent to VMO'之前,我们需要计数值。
SQL> Select * from sample_test;
ID CONTRACT_ID STAT_NEW UPD_DT
----------------------------- -------------------------------------- ----------
0 CR 01 to MWO 1 Sent to xxxx Project Team 11-AUG-13
1 CR 01 to MWO 1 Sent to xxxx Project Team 11-AUG-13
2 CR 01 to MWO 1 Sent to xxxx Project Team 11-AUG-13
3 CR 01 to MWO 1 Sent to VMO 12-AUG-13
4 CR 01 to MWO 1 Sent to xxxx Project Team 11-AUG-13
5 CR 01 to MWO 1 Sent to xxxx Project Team 11-AUG-13
6 CR 01 to MWO 1 Sent to VMO 12-AUG-13
7 CR 01 to MWO 2 Sent to xxxx Project Team 11-AUG-13
8 CR 01 to MWO 2 Sent to xxxx Project Team 11-AUG-13
9 CR 01 to MWO 2 Sent to xxxx Project Team 11-AUG-13
10 CR 01 to MWO 2 Sent to VMO 12-AUG-13
11 CR 01 to MWO 3 Sent to xxxx Project Team 12-AUG-13
12 CR 01 to MWO 3 Sent to xxxx Project Team 12-AUG-13
13 CR 01 to MWO 3 Sent to VMO 13-AUG-13
7 rows selected
我已尝试过下面的方案,如果给出了特定的合同ID,如果只有一个发送给VMO,则下面的方案正在运行。
select count(*) from sample_test where upd_dt <= (select UPD_DT from sample_test where stat_new='Sent to VMO' and contract_id='CR 01 to MWO 1') AND stat_new='Sent to xxxx Project Team';
我的预期输出如下......
CONTRACT_ID count of STAT_NEW='Sent to xxxx Project Team'
-------------- ------------
CR 01 to MWO 1 3
CR 01 to MWO 1 2
CR 01 to MWO 2 3
CR 01 to MWO 3 2
答案 0 :(得分:1)
这比看起来有点棘手。以下应该有效:
select contract_id, sum(case when stat = 'Sent to xxxx Project Team' then 1 else 0 end)
from (select t.*,
sum(case when stat = 'Sent to VMO' then 1 else 0 end) over
(partition by Contract_Id order by id desc) as SentVMOcount
from sample_test t
) t
where sentVMOcount = 1
group by contract_id;
这里的关键是sentVMOcount
。这使用累积和解析函数根据该行之后发生的'Sent to VMO'
状态枚举行。因此,所有最终行的计数都为1.外部查询选择这些并进行适当的聚合。
答案 1 :(得分:1)
试试这个
SELECT CONTRACT_ID,COUNT(STAT_NEW) STAT_NEW_COUNT FROM
(
SELECT t.*
,(SELECT COUNT(id) FROM #MyTable WHERE STAT_NEW='Sent to VMO' AND ID < t.ID) AS cnt
from #MyTable t
WHERE STAT_NEW<>'Sent to VMO'
) tt
GROUP BY CONTRACT_ID,cnt
<强>输出强>
CONTRACT_ID STAT_NEW_COUNT
CR 01 to MWO 1 3
CR 01 to MWO 1 2
CR 01 to MWO 2 3
CR 01 to MWO 3 2