2017-09-12 21 views
1

私の親テーブルは以下の通りです:SQLクエリが必要です。 SQL 10g | ORACE

Date  Month PRICE product contract_month Contract_year 
7-Jun-17 17-Sep -79  XYZ  9    2017 
7-Jun-17 17-Oct -75  XYZ  10    2017 
7-Jun-17 17-Jul -92  XYZ  7    2017 
7-Jun-17 17-Aug -90  XYZ  8    2017 
7-Jun-17 18-Sep -95  XYZ  9    2018 
7-Jun-17 18-Oct -96  XYZ  10    2018 
7-Jun-17 18-Nov -97  XYZ  11    2018 

は、クエリの下に実行午前:

SELECT opr_date,contract,price 
       FROM table 
       WHERE date = '07-jun-2017' 
         AND product = 'XYZ' 
         ANd contract_year = 2017 
         AND contract_month between 1 and 12 

私のクエリは、この結果を引き出している:

Date  Month PRICE 
7-Jun-17 17-Sep -79 
7-Jun-17 17-Oct -75 
7-Jun-17 17-Jul -92 
7-Jun-17 17-Aug -90 

をしかし、それは価格を移入する必要があり四半期のすべての3ヶ月が存在する場合に限ります。 上記の例では、7月と8月の価格があります。そのため、価格は3四半期に3ヶ月間存在します。したがって、それはそれぞれの価格を入力する必要があります。 しかし、第4四半期、すなわち10月、11月、12月(contract_month = 10,12)の場合、oct価格のみが存在します。だから私のクエリは、この価格を設定してはいけません、またはそれは(価格は親テーブルのnovとdecには存在しないので)nullとして設定する必要があります。

答えて

1

は年によって四半期を決定し、(数= 3有するグループによる)の結果を数える:

select opr_date,contract,price 
    from your_table 
where /* your conditions ... */ 
    date = '07-jun-2017' 
and product = 'XYZ' 
and contract_year = 2017 
and contract_month between 1 and 12 
/* only rows, where exist 3 rows per quarter */ 
and case 
    when contract_month between 1 and 3 then 
    contract_year * 10 + 1 
    when contract_month between 4 and 6 then 
    contract_year * 10 + 2 
    when contract_month between 7 and 9 then 
    contract_year * 10 + 3 
    else 
    contract_year * 10 + 4 
end in (select quarter 
      from (select case 
          when contract_month between 1 and 3 then 
          contract_year * 10 + 1 
          when contract_month between 4 and 6 then 
          contract_year * 10 + 2 
          when contract_month between 7 and 9 then 
          contract_year * 10 + 3 
          else 
          contract_year * 10 + 4 
         end as quarter 
        from your_table) 
      group by quarter 
     having count(*) = 3); 
+0

おかげフランクOckenfussを! –

関連する問題