2011-05-26 65 views
2

假如我是如下图所示获取数据

ACT_NO  DATE1   AMOUNT 
12111201 2/1/2009  66600.00 
12111201 8/31/2009 66600.00 
12111201 7/29/2008 133200.00 
12111201 5/19/2009 66600.00 

我需要得到量的总和为2009年特定年份即从2009年1月31日于具有数据31/12/2009年。 我如何得到每年? date1字段在oracle中是日期格式。我使用的PL SQL开发

回答

1

只要DATE1没有时间组件,你可以使用:

where date1 between date '2009-01-01' and '2009-12-31' 

可以在DATE1使用索引。另一个解决方案(不能在date1上使用简单索引)为:

where trunc(date1,'YYYY') = date '2009-01-01' 
1

此查询将给定年份的AMT列总和。在结果中包含YEAR是可选的;如果你不需要它,你也不需要GROUP BY子句。

select to_char(date1, 'YYYY') as year 
     , sum(amount) as year_total 
from your_table 
where date1 between to_date('01-JAN-2009', 'DD-MON-YYYY') 
       and to_date('31-DEC-2009 23:59:59', 'DD-MON-YYYY HH24:MI:SS') 
group by to_char(date1, 'YYYY')  
/

查询假定DATE1具有DATE数据类型并且包括时间元素(因此在附加格式和臂的BETWEEN子句)。如果DATE1不够礼貌,那么最简单的kludge就是要首先将它列入日期。

+0

TRUNC(date1,'YY')是TO_CHAR的替代方法 – 2011-05-27 03:32:54

0
with sampleData as(
select 12111201 ACT_NO, to_date('2/1/2009' ,'mm/dd/rrrr') DATE1 , 66600.00 AMOUNT from dual union all 
select 12111201 ACT_NO, to_date('8/31/2009','mm/dd/rrrr') DATE1 , 66600.00 AMOUNT from dual union all 
select 12111201 ACT_NO, to_date('7/29/2008','mm/dd/rrrr') DATE1 , 133200.00 AMOUNT from dual union all 
select 12111201 ACT_NO, to_date('5/19/2009','mm/dd/rrrr') DATE1 , 66600.00 AMOUNT from dual 
) 

select extract(year from date1) date1_year 
     ,sum(amount) amount_summed 
     ,count(distinct ACT_NO) distinctAccounts 
     , count(*) total_occurrences 
    from sampleData 

/*其中TO_DATE之间DATE1('01 -JAN-2009' , 'DD-MON-YYYY') 和TO_DATE('31-DEC-2009 23时59' 分59秒,“DD- MON-YYYY HH24:MI:SS')*/--from @ APC的答案

group by extract(year from date1) 
/

DATE1_YEAR    AMOUNT_SUMMED   DISTINCTACCOUNTS  TOTAL_OCCURRENCES  
---------------------- ---------------------- ---------------------- ---------------------- 
2008     133200     1      1      
2009     199800     1      3 

您也可以尽管除非你想创建函数的索引使用extract(year from dateField)

,利用@ APC的或@托尼安德鲁斯'是今年过滤的方式。