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 に送信されたものが 1 つしかない場合は、以下のシナリオが機能しています。

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'これは、累積合計分析関数を使用して、その行の後に発生するステータスに基づいて行を列挙します。So, all the final rows get a count of 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 に答える