从IF THEN ELSE子句中独立运行select

时间:2017-05-24 09:03:29

标签: sql oracle oracle11g

我有这个问题:

tokenize

给出了我需要的结果:

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;
/

但是我需要添加一些像这样的查询。这些应该独立于IF THEN ELSE子句中的选择运行,因此我不需要它在IF THEN ELSE中:

FLARE_MTD_KNM3
86751.8733412651

我希望得到如下内容:

   select sum(max(case when code = 'U900' then volume else  null end )) CORR
     from BALANCE_YEAR1
         where production_day between trunc(Date_Parameter, 'YEAR') and Max_month 
              group by production_day

我在想下面的内容,但它不起作用:

FLARE_MTD_KNM3    CORR
86751.8733412651  2387

1 个答案:

答案 0 :(得分:1)

这似乎会为您提供所需的输出

DECLARE
   Date_Parameter date;
   Max_Month date;
   l_corr BALANCE_YEAR.volume%type;
BEGIN
  Date_Parameter := DATE '2017-04-01';
  select max(month) into Max_month from BALANCE_YEAR2;

  select sum(max(case when code = 'U900' then volume else  null end )) CORR
  into l_corr
  from BALANCE_YEAR1
  where production_day between trunc(Date_Parameter, 'YEAR') and Max_month 
  group by production_day;

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

请注意,我在BALANCE_YEAR1上保留了查询的逻辑。不知道你的数据我认为这将返回一行。但是如果production_day有多个值,那么您可能需要重新访问GROUP BY子句(或WHERE条件)。