2017-03-14 56 views
2

我的表像需要編寫子查詢來計算收入每月

summa_som  date_operation 
    -----  -------------- 
    100  11/03/2005 
    500  13/07/2008 
    900  12/11/2015 

預期結果

我要計算每月的收入應該有3列: 收入,月和年:

Income  Month  Year 
------  --------  ---- 
10000  February  2015  
15000  December  2015 

我試過這個,但是,我不明白子查詢是如何工作的。此代碼應該給我想要的東西的想法:

select max(summa_som * 0.01) income 
from t_operation 
where to_char(date_operation,'MM') = 11 
and to_char(date_operation,'YYYY') = 2015 
(select max(summa_som * 0.01) income_for_dec2015 from t_operation 
where to_char(date_operation,'MM') = 12 
and to_char(date_operation,'YYYY') = 2015) 

回答

3

您可以使用過濾和聚集來實現這一目標:

select to_char(date_operation, 'Month') as mn, 
    to_char(date_operation, 'YYYY') as yr, 
    max(summa_som) * 0.01 as income 
from t_operation 
where date_operation >= date '2015-11-01' 
    and date_operation < date '2016-01-01' 
group by to_char(date_operation, 'Month'), 
    to_char(date_operation, 'YYYY') 

如果你想把所有的幾個月和幾年的結果,其數據是目前,您可以刪除過濾條件。

+0

非常感謝 – vesperkg

0

您對日期有一些特定的格式問題,並且將收入乘以0.01就會產生一些問題。當你有這樣的格式問題時,我更喜歡根據涉及的數據類型在內部查詢中進行聚合,將數字保存爲數字和日期,甚至將其修改爲日期分組。然後,使用處理類型轉換或格式的外部查詢來包裝語句。

select (income*0.01) as income_value, 
     to_char(income_mn,'Month') as income_month, 
     to_char(income_mn,'YYYY') as income_year 
from (
     select trunc(date_operation,'MON') as income_mn, 
      max(summa_som) as income 
     from t_operation 
     where date_operation between to_date('11/2015','MM/YYYY') 
           and to_date('01/2016','MM/YYYY') - numtodsinterval(1, 'SECOND') 
     group by trunc(date_operation,'MON') 
    ); 

注意:使用介於兩者之間使得包含上限值和下限值。我已經減去了一秒鐘的上限,只包括12月份的價值,但除非你只想要2015年的價值,否則這並不是真的必要。