0

我有下表,在这里,我想获取值 STAT_NEW = 'Sent to xxxx Project Team' 的计数。在出现值 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
4

2 回答 2

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。外部查询选择这些行并进行适当的聚合。

于 2013-08-13T11:18:07.313 回答
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
于 2013-08-13T11:53:40.043 回答