在SQL中按月求和

时间:2012-10-16 13:36:44

标签: sql

我试图按月汇总我的每日数据(截断(DM_OWNER.LD_LEG_DW.CPLD_DTT)。这是在Web Intelligence BI报告中创建的。

SELECT
  DM_OWNER.LD_LEG_DW.LGST_GRP_CD,
  DM_OWNER.LGST_GRP_T.LGSTGRP_DESC,
  DM_OWNER.LD_LEG_DW.CARR_CD,
  DM_OWNER.LD_LEG_DW.LD_LEG_ID,
  DM_OWNER.LD_LEG_DW.BILL_TO_CUST_CD,
  trunc(DM_OWNER.LD_LEG_DW.CPLD_DTT),
  trunc(DM_OWNER.VCHR_AP_T.CRTD_DTT),
  AP_Detail.PYMNT_AMT_DLR
FROM
  DM_OWNER.LD_LEG_DW,
  DM_OWNER.LGST_GRP_T,
  DM_OWNER.VCHR_AP_T,
  DM_OWNER.CHRG_DETL_T_NOTOTAL_V  AP_Detail
WHERE
  ( DM_OWNER.LD_LEG_DW.LD_LEG_ID=DM_OWNER.VCHR_AP_T.LD_LEG_ID(+)  )
  AND  ( DM_OWNER.VCHR_AP_T.VCHR_NUM=AP_Detail.VCHR_NUM_AP  )
  AND  ( DM_OWNER.LD_LEG_DW.LGST_GRP_CD=DM_OWNER.LGST_GRP_T.LGST_GRP_CD  )
  AND  
  (
   DM_OWNER.LD_LEG_DW.LGST_GRP_CD  In  ( 'PBRK'  )
   AND
   trunc(DM_OWNER.VCHR_AP_T.CRTD_DTT)  >=  '01-10-2012 00:00:00'
  )

2 个答案:

答案 0 :(得分:2)

如果没有明确的字段名称或数据结构的解释,这太模糊了。但原则是

select 
     displayfields,
     year(datefield), month(datefield), 
     sum(valuefield)
from yourtable
group by 
     displayfields,
     year(datefield), month(datefield), 

答案 1 :(得分:0)

没有深入了解您的查询细节,这是一般方法。

CAST很讨厌,但这样做的好处就是给你一个实际的DATETIME作为石斑鱼。

SELECT
   SUM(Amount) AS MonthTotal,
   CAST(CAST(YEAR(DateCollected) AS VARCHAR(4)) 
     + '/' + CAST(MONTH(DateCollected) AS VARCHAR(2)) 
     + '/01' AS DATETIME) AS PaymentMonth
FROM
   PaymentsReceived
GROUP BY
   CAST(CAST(YEAR(DateCollected) AS VARCHAR(4)) 
     + '/' + CAST(MONTH(DateCollected) AS VARCHAR(2)) + '/01' AS DATETIME)