Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 需要编写子查询来计算每个月的收入_Sql_Oracle_Oracle11g - Fatal编程技术网

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

Sql 需要编写子查询来计算每个月的收入,sql,oracle,oracle11g,Sql,Oracle,Oracle11g,我的桌子像 summa_som date_operation ----- -------------- 100 11/03/2005 500 13/07/2008 900 12/11/2015 预期结果 我想计算每个月的收入,应该有3列: 收入,月份和年份: Income Month Year ------ -------- ---- 10000 February

我的桌子像

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 ) 

您可以使用过滤器和聚合来实现这一点:

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')
选择将字符(日期操作,'Month')作为mn,
将字符(日期操作“YYYY”)转换为yr,
最大值(总和)*0.01作为收入
从t_操作
其中,操作日期>=日期“2015-11-01”
和运行日期<日期“2016-01-01”
分组依据至字符(日期操作,“月”),
to_char(日期操作'yyy')

如果您想要显示数据所在的所有月份和年份的结果,您可以删除筛选条件。

通过将其乘以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将使上限值和下限值都包含在内。我在上限上减去了1秒,只包含12月份的值,但这并不是必须的,除非您只想要2015年的值。

非常感谢您