How to group by month from Date field using sql

前端 未结 10 1952
自闭症患者
自闭症患者 2020-11-30 23:39

How can I group only by month from a date field (and not group by day)?

Here is what my date field looks like:

2012-05-01

Here is m

相关标签:
10条回答
  • 2020-12-01 00:28

    Use the DATEPART function to extract the month from the date.

    So you would do something like this:

    SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
    FROM t
    GROUP BY DATEPART(month, Closing_Date)
    
    0 讨论(0)
  • 2020-12-01 00:29

    By Adding MONTH(date_column) in GROUP BY.

    SELECT Closing_Date, Category,  COUNT(Status)TotalCount
    FROM   MyTable
    WHERE  Closing_Date >= '2012-02-01' AND Closing_Date <= '2012-12-31'
    AND    Defect_Status1 IS NOT NULL
    GROUP BY MONTH(Closing_Date), Category
    
    0 讨论(0)
  • 2020-12-01 00:33

    You can do this by using Year(), Month() Day() and datepart().

    In you example this would be:

    select  Closing_Date, Category,  COUNT(Status)TotalCount from  MyTable
    where Closing_Date >= '2012-02-01' and Closing_Date <= '2012-12-31' 
    and Defect_Status1 is not null 
    group by Year(Closing_Date), Month(Closing_Date), Category
    
    0 讨论(0)
  • 2020-12-01 00:33

    Try the Following Code

    SELECT  Closing_Date = DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), 
            Category,  
            COUNT(Status) TotalCount 
    FROM    MyTable
    WHERE   Closing_Date >= '2012-02-01' 
    AND     Closing_Date <= '2012-12-31'
    AND     Defect_Status1 IS NOT NULL
    GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), Category;
    
    0 讨论(0)
提交回复
热议问题