使用案例条件时摆脱重复

时间:2017-05-23 08:32:18

标签: sql oracle oracle11g

我有以下查询:

declare
Balance_Year_Sub1_cursor Reports.rep_type;
Date_Parameter date;
  BEGIN
Date_Parameter := '01-Apr-2017';

OPEN Gas_Balance_Year_Sub1_cursor FOR

select case when Date_Parameter <= (select max(month) from BALANCE_YEAR2) then 
(
   select sum(FLARE_MTD_KNM3) FLARE_MTD_KNM3 from BALANCE_YEAR2
   where (month between trunc(Date_Parameter, 'YEAR') and  LAST_DAY(ADD_MONTHS(date_parameter,0))) 

) 
   else  
(    
  select NET_VOL_MTD_KNM3 from STREAM_D where code = 'FLARE' 
  and production_day = LAST_DAY(trunc(Date_Parameter))
) 
  end FLARE_MTD_KNM3 from BALANCE_YEAR2;


               :to_grid := Balance_Year_Sub1_cursor;
END;
/

它给出的值是正常的,但是为BALANCE_YEAR2的行数生成重复项,如何去掉它们:

FLARE_MTD_KNM3 
86751.8733412651
86751.8733412651
86751.8733412651
86751.8733412651
86751.8733412651

1 个答案:

答案 0 :(得分:1)

您的案例表达式是从BALANCE_YEAR2中选择的,因此您将为该表中的每一行获取一行输出,无论您遇到的案例中的哪一个分支 - 结果中每行的值set将是相同的,可以是针对同一个表的第二个查询的总和,也可以是来自STREAM_D的单个净值。

您可以单独查询最大月份值,然后使用简单的IF检查来决定选择哪个表格查询:

DECLARE
   Date_Parameter date;
   Max_Month date;
BEGIN
  Date_Parameter := DATE '2017-04-01';
  select max(month) into Max_month from BALANCE_YEAR2;

  IF Date_Parameter <= Max_month THEN
    OPEN :to_grid FOR
      select sum(FLARE_MTD_KNM3) FLARE_MTD_KNM3
      from BALANCE_YEAR2
      where month between trunc(Date_Parameter, 'YEAR')
        and LAST_DAY(date_parameter);
  ELSE
    OPEN :to_grid FOR
      select NET_VOL_MTD_KNM3
      from STREAM_D
      where code = 'FLARE' 
      and production_day = LAST_DAY(Date_Parameter);
  END IF;
END;
/

或者您可以在联合的每个分支中包含最长月份查询:

DECLARE
  Date_Parameter date;
BEGIN
  Date_Parameter := DATE '2017-04-01';

  OPEN :to_grid FOR
    select sum(FLARE_MTD_KNM3) FLARE_MTD_KNM3
    from BALANCE_YEAR2
    where month between trunc(Date_Parameter, 'YEAR')
      and LAST_DAY(date_parameter) 
    and Date_Parameter <= (select max(month) from BALANCE_YEAR2)
    union all
    select NET_VOL_MTD_KNM3
    from STREAM_D
    where code = 'FLARE' 
    and production_day = LAST_DAY(Date_Parameter)
    and Date_Parameter > (select max(month) from BALANCE_YEAR2);
END;
/

在这两种情况下,我都删除了一些不必要的add_months / trunc调用,更改了固定日期分配以使用日期文字,而不是依赖隐式转换和您的NLS设置,并打开{ {1}}直接绑定变量游标而不是使用中间to_grid(可能是游标)变量。