T sql group by month

时间:2015-04-17 13:47:02

标签: sql-server

我正在尝试根据从datetime

进行分组

我在查询

下面运行
select  cf.flow_name as 'Process', COUNT(c.case_ID) as 'Case', CONVERT(VARCHAR(10),c.xdate,104) as 'Date' 
from cases c inner join case_flow cf  on c.case_flow_ID=cf.CF_ID 
where    project_ID=1 and c.subject_ID=1
group by cf.flow_name,c.xdate 

列数据类型如下

flow_name varchar(100)

case_ID int

xdate datetime

如果我在查询

之上运行,结果显示如下

流程 - 案例 - 日期

Test      1  30.01.2015
Test      1  30.01.2015
analysis  1  19.03.2015
analysis  1  30.03.2015
analysis  1  13.04.2015
analysis  1  16.04.2015

问题:

我需要分组如下(按照x.date的月份分组)

正确结果 应如下所示

流程 - 案例 - 日期

Test      2  30.01.2015 (Because Test has 2 data from 01 month)
analysis  2  19.03.2015 (Because analysis has 2 data from 03 month)
analysis  2  13.04.2015 (Because analysis has 2 data from 04 month)

如上所述,所有结果应按月分组,如何根据我的查询执行此操作?

希望你理解我的英语谢谢

1 个答案:

答案 0 :(得分:1)

SELECT cf_flow, 
       Count(*), 
       Min(xdate) 
FROM   cases c 
       INNER JOIN case_flow cf 
               ON c.case_flow_id = cf.cf_id 
WHERE  project_id = 1 
       AND c.subject_id = 1 
GROUP  BY cf_flow, 
          Dateadd(month, Datediff(month, 0, xdate), 0)