2017-09-12 3 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 =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을! –