显示不同产品的不同聚合

时间:2015-09-21 10:33:50

标签: oracle stored-procedures oracle11g

我想要一个用于按产品生成聚合产品的代码。产品总量可以是年初至今(YTD),月至今(MTD)和季度至今(QTD)。用户将在此基础上传递参数,代码应决定用户想要的输出类型。

If the Year is passing in the parameter than the code should generate the aggregate from the starting of the year to the sysdate.

If the Quarter No is passing in the parameter than the code should generate the aggregate from the starting of the quarter to the sysdate.

If the Month is passing in the parameter than the code should generate the aggregate from the starting of the month to the sysdate.

这意味着在参数的基础上它应该能够决定哪些用户想要那些3.我的输入数据是这样的 -

Product Table

    Product_ID       Product_name          Price
    1                  Mobile               200
    2                   T.V.                400
    3                  Mixer                300

销售表 -

 Product_ID          Sales_Date         Quantity
    1                   01-01-2015            30
    2                   03-01-2015            40
    3                   06-02-2015            10
    1                   22-03-2015            30
    2                   09-04-2015            10
    3                   21-05-2015            40
    1                   04-06-2015            40
    2                   29-07-2015            30
    1                   31-08-2015            30
    3                   14-09-2015            30

我的输出列包含3列,即Product_id,Product_Name和Total。 Total_Amount(数量*价格)列必须根据用户给出的输入计算销售额,并且是这样的 - 例如,

 If pro_test is the procedure then 
call pro_test('YTD') -- Should Return the ProductWise YTD,
call pro_test('QTD') -- Should Return the ProductWise QTD and so on..

1 个答案:

答案 0 :(得分:0)

您正在寻找WHERE条款:-)使用OR列出您的条件,您就完成了。

select 
  p.product_id, 
  p.product_name, 
  coalesce(sum(s.quantity * p.price), 0) as total
from product p 
left join sales s on s.product_id = p.product_id
where 
  (:aggregate = 'YTD' and to_char(s.sales_date, 'yyyy') = to_char(sysdate, 'yyyy'))
or
  (:aggregate = 'MTD' and to_char(s.sales_date, 'yyyymm') = to_char(sysdate, 'yyyymm'))
or
  (:aggregate = 'QTD' and to_char(s.sales_date, 'yyyyq') = to_char(sysdate, 'yyyyq'))
group by p.product_id, p.product_name;

编辑:以下是相应的PL / SQL函数的样子:

create or replace function matches_date_aggregate(in_sales_date date, in_aggregate char) 
  return integer as
begin
  if (in_aggregate = 'YTD' and to_char(in_sales_date, 'yyyy') = to_char(sysdate, 'yyyy'))
  or (in_aggregate = 'MTD' and to_char(in_sales_date, 'yyyymm') = to_char(sysdate, 'yyyymm'))
  or (in_aggregate = 'QTD' and to_char(in_sales_date, 'yyyyq') = to_char(sysdate, 'yyyyq')) then
    return 1;
  else
    return 0;
  end if;
end matches_date_aggregate;

您的查询的WHERE子句将变为:

where matches_date_aggregate(s.sales_date, :aggregate) = 1

遗憾的是,该函数无法返回BOOLEAN,因为即使Oracle的PL / SQL知道BOOLEAN数据类型,Oracle SQL也不知道。