一列计算多个输出

时间:2015-09-18 11:15:15

标签: oracle oracle11g

我已经显示了年初至今(年初至今),QTD(季度至今)和MTD(月初至今)的总产品销售额。事情是我必须只展示其中一个。在选择的基础上只能看到一个输出,即我们有单选按钮从多个中选择一个。这里还给出输入以选择并基于该输入生成输出。输入可以是任何YTD,QTD或MTD。输出基于输入生成。我不知道如何计算输入可以变化的列输出。 我有一个产品表 -

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 and Total_Amount。  列Total_Amount(数量*价格)必须根据用户给出的输入计算销售额,即

IF it is YTD then it should calculate the total sale from Starting Date of Year ( 01-01-2015) to the current_date(sysdate),

IF it is QTD then in which quarter the current date is falling i.e if current month is september then from 1 July to current_date(sysdate),

IF it is MTD then in which month the current date is falling to the current_date(sysdate).

任何人都可以提供帮助。感谢!!!

2 个答案:

答案 0 :(得分:0)

我的假设是你有3个单选按钮(变量:YTD,:QTD,在我的例子中为MTD),用户一次只能选择一个值,其余值为空。

你可以使用这样的东西来得到你想要的东西:

select SUM(a.QTY*B.PRICE) from PRODUCTS a
inner join SALES B on a.PRODUCT_ID=B.PRODUCT_ID
where 
(:YTD is null or B.SALES_DATE between '01-JAN-15' and sysdate)
and
(:QTD is null or TO_CHAR(B.SALES_DATE, 'YYYY-Q')=TO_CHAR(sysdate, 'YYYY-Q'))
and
(:MTD is null or TO_CHAR(B.SALES_DATE, 'MM')=TO_CHAR(sysdate, 'MM'));

您可以在此处 sqlfiddle

进行测试

答案 1 :(得分:0)

-- step 1
create or replace view my_admin
as
select 'YTD' element, product_id,  sum(quantity) sum_quantity   
from sales
where Sales_date  between trunc(sysdate,'Y') and sysdate
group by product_id 
union
select 'QTD', product_id, sum(quantity) sum_quantity  
from sales
where Sales_date  between trunc(sysdate,'Q') and sysdate
group by product_id
union
select 'MTD', product_id, sum(quantity) sum_quantity  
from sales
where Sales_date  between trunc(sysdate,'MM') and sysdate
group by product_id



-- step 2
select element, p.product_name,  (sum_quantity * p.PRICE) agregate
from my_admin a
inner join products p  on a.product_id = p.product_id  
where element = (:input)