【问题标题】:Need SQL query | SQL 10g | Orace需要SQL查询 | SQL 10g |甲骨文
【发布时间】:2017-09-12 06:03:21
【问题描述】:

我的父表如下:

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

但当且仅当该季度的所有三个月都存在时,它才应该填充价格。 在上面的例子中:我们有 6 月和 8 月的价格。因此,第三季度所有 3 个月的价格都存在。所以它应该填充相应的价格。 但是对于第 4 季度,即 Oct,Nov 和 dec (contract_month = 10,11 &12) 月份,仅存在 oct 价格。所以我的查询不应该填充这个价格或者它应该填充为空(因为价格在父表中不存在 nov 和 dec)。

【问题讨论】:

    标签: sql oracle oracle10g


    【解决方案1】:

    逐年确定季度并计算结果(分组依据,count=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);
    

    【讨论】:

    • 谢谢弗兰克·奥肯福斯!!
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    相关资源
    最近更新 更多