日期:2014-05-17  浏览次数:21491 次

如何写求季度累计求和SQL语句
我想按照季度求和

当输入201002时求 01,02的和
当输入201006时求 04,05,06的和
当输入201008时求 07,08的和
以此类推...代码类似如下,但是这个语句出错
大家帮帮我怎么写这个SQL

Java code

   SELECT '200902' DATE_ID,
       T_COPLAN.MANAGECOM_ID MANAGECOM_ID,
       SUM(T_COPLAN."VALUE") VALUE
   FROM T_COPLAN  T_COPLAN
   WHERE T_COPLAN.DEPT_ID = 1
   AND T_COPLAN.SUBJECT_ID = 1
   AND length(T_COPLAN.DATE_ID) = 6
   AND length(T_COPLAN.MANAGECOM_ID) = 4
   AND(  case 
         when substr('200902',5,2) in ('01','02','03') then 
         to_date(T_COPLAN.DATE_ID, 'yyyymm') BETWEEN 
         to_date(substr('200902', 1, 4) || '01', 'YYYYMM') AND
         to_date('200902', 'YYYYMM')
         when substr('200902',5,2) in ('04','05','06') then 
         to_date(T_COPLAN.DATE_ID, 'yyyymm') BETWEEN 
         to_date(substr('200902', 1, 4) || '04', 'YYYYMM') AND
         to_date('200902', 'YYYYMM')
         when substr('200902',5,2) in ('07','08','09') then 
         to_date(T_COPLAN.DATE_ID, 'yyyymm') BETWEEN 
         to_date(substr('200902', 1, 4) || '07', 'YYYYMM') AND
         to_date('200902', 'YYYYMM')
         when substr('200902',5,2) in ('10','11','12') then 
         to_date(T_COPLAN.DATE_ID, 'yyyymm') BETWEEN 
         to_date(substr('200902', 1, 4) || '10', 'YYYYMM') AND
         to_date('200902', 'YYYYMM')
         end 
    )
   group by T_COPLAN.MANAGECOM_ID




------解决方案--------------------
SQL code
SELECT '200902' DATE_ID, T_COPLAN.MANAGECOM_ID MANAGECOM_ID, SUM(T_COPLAN."VALUE") VALUE
  FROM T_COPLAN T_COPLAN
 WHERE T_COPLAN.DEPT_ID = 1 AND
       T_COPLAN.SUBJECT_ID = 1 AND
       length(T_COPLAN.DATE_ID) = 6 AND
       length(T_COPLAN.MANAGECOM_ID) = 4 AND
       to_date(T_COPLAN.DATE_ID, 'yyyymm') BETWEEN trunc(to_date('200902', 'yyyymm'), 'Q') AND
       last_day(to_date('200902', 'yyyymm'))
 GROUP BY T_COPLAN.MANAGECOM_ID

------解决方案--------------------
SELECT '200902' DATE_ID,
T_COPLAN.MANAGECOM_ID MANAGECOM_ID,
SUM(T_COPLAN."VALUE") VALUE
FROM T_COPLAN T_COPLAN
WHERE T_COPLAN.DEPT_ID = 1
AND T_COPLAN.SUBJECT_ID = 1
AND length(T_COPLAN.DATE_ID) = 6
AND length(T_COPLAN.MANAGECOM_ID) = 4
and (T_COPLAN.DATE_ID>=to_char(trunc(to_date('200902','yyyymm'),'q'),'yyyymm')
and t_coplan.date_id<to_char(add_months(trunc(to_date('200902','yyyymm'),'q'),3),'yyyymm'))
group by T_COPLAN.MANAGECOM_ID