在查询中使用多个和案例行

时间:2014-03-31 16:12:19

标签: sql

这段代码完全符合我所需要的几个月。基本上提供NumeratorDenominator

SUM(CASE WHEN smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date BETWEEN '2013-01-01' and             '2013-01-31'  THEN 1 ELSE 0 END) AS Total_Jan13,
SUM(CASE WHEN smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date BETWEEN '2013-01-01' and '2013-01-31' and [ind_ra_cfvmc_00-30] = 'YES' THEN 1 ELSE 0 END) AS RA_Jan13,
SUM(CASE WHEN smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date BETWEEN '2013-02-01' and '2013-02-28'  THEN 1 ELSE 0 END) AS Total_Feb13,
SUM(CASE WHEN smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date BETWEEN '2013-02-01' and '2013-02-28' and [ind_ra_cfvmc_00-30] = 'YES'   THEN 1 ELSE 0 END) AS RA_Feb13,
SUM(CASE WHEN smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date BETWEEN '2013-03-01' and '2013-03-31'  THEN 1 ELSE 0 END) AS Total_Mar13,

当你有多个月时,它会变得相当繁琐...是否有更有效的方法来执行此计算?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以按年份和月份将其分组,然后操作:

SELECT DATEPART(year,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date) AS TotalYear, 
       DATEPART(month,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date) AS TotalMonth, 
       COUNT(*) AS Total
FROM [table]
GROUP BY DATEPART(year,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date), 
       DATEPART(month,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date)

这将按月向您提供总计,而无需事先指定月份。