需要编写子查询来计算每个月的收入

时间:2017-03-14 04:46:44

标签: sql oracle oracle11g

我的表就像

utils.py

预期结果

我想计算每个月应该有3列的收入: 收入,月份和年份:

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

我试过这个但是,我不太清楚子查询是如何工作的。这段代码应该让我知道我想要的东西:

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

2 个答案:

答案 0 :(得分:4)

您可以使用过滤器和聚合来实现此目的:

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')

如果您想要数据存在的所有月份和年份的结果,您可以删除过滤条件。

答案 1 :(得分: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')
     );

注意:使用between会使上限值和下限值都包含在内。我已经减去了一秒钟的上限只包含12月的价值,但除非你只想要2015年的价值,否则这不是必要的。