如何将个别日期分组为几个月

时间:2013-04-25 22:31:52

标签: sql sql-server syntax-error

我试图按月汇总这些数据的结果...而不是个别日期。我怎么能这样做?

SELECT DISTINCT 
    CONVERT (DATETIME, CONVERT (VARCHAR (10), SignInDateTime, 101)) AS Appended_SignInDate,
    GO.GeographicLocationDescription,
    COUNT(DISTINCT acd.EmployeeID) as Total_FTL

FROM    
    dbACD.Detail.vwRockwellEventAgentPerformance AS ACD

LEFT OUTER JOIN     
    dbEmployee.Summary.vwEmployeeHistory AS EH 
    ON acd.employeeID = eh.EmployeeID
    AND ACD.SignOutDateTime Between eh.StartDate and eh.EndDate

LEFT OUTER JOIN     
    dbEmployee.Config.vwGeographicLocation AS GO
    ON EH.GeographicLocationID = GO.GeographicLocationID


WHERE   
    ACD.SignOutDateTime BETWEEN '2012-06-01' AND '2013-03-31'
--  AND ACD.SignoutReasonCode ='4'
    AND GO.GeographicLocationDescription is not null

GROUP BY    

    CONVERT (DATETIME, CONVERT (VARCHAR (10), SignInDateTime, 101)),
    GO.GeographicLocationDescription


ORDER BY    
    CONVERT (DATETIME, CONVERT (VARCHAR (10), SignInDateTime, 101)), 
    GO.GeographicLocationDescription

1 个答案:

答案 0 :(得分:1)

DatePart()函数应该适用于此。

http://msdn.microsoft.com/en-us/library/ms174420.aspx

SELECT DISTINCT 
    DATEPART(month, CONVERT (DATETIME, CONVERT (VARCHAR (10), SignInDateTime, 101))) AS Appended_SignInDate
    , GO.GeographicLocationDescription, COUNT(DISTINCT acd.EmployeeID) as Total_FTL
FROM dbACD.Detail.vwRockwellEventAgentPerformance AS ACD
LEFT OUTER JOIN dbEmployee.Summary.vwEmployeeHistory AS EH 
     ON acd.employeeID = eh.EmployeeID 
     AND ACD.SignOutDateTime Between eh.StartDate and eh.EndDate
LEFT OUTER JOIN dbEmployee.Config.vwGeographicLocation AS GO 
     ON EH.GeographicLocationID = GO.GeographicLocationID
WHERE ACD.SignOutDateTime BETWEEN '2012-06-01' AND '2013-03-31' 
 -- AND ACD.SignoutReasonCode ='4' AND GO.GeographicLocationDescription is not null
GROUP BY 
     DATEPART(month, CONVERT (DATETIME, CONVERT (VARCHAR (10), SignInDateTime, 101)))
   , GO.GeographicLocationDescription

ORDER BY
CONVERT (DATETIME, CONVERT (VARCHAR (10), SignInDateTime, 101)), GO.GeographicLocationDescription