zoukankan      html  css  js  c++  java
  • How to group by month from Date field using sql

    How to group by month from Date field using sql

    问题

    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 my current SQL:

    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  Closing_Date, Category
    

    回答1

    I would use this:

    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;
    

    This will group by the first of every month, so

    `DATEADD(MONTH, DATEDIFF(MONTH, 0, '20130128'), 0)` 
    

    will give '20130101'. I generally prefer this method as it keeps dates as dates.

    Alternatively you could use something like this:

    SELECT  Closing_Year = DATEPART(YEAR, Closing_Date),
            Closing_Month = DATEPART(MONTH, 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 DATEPART(YEAR, Closing_Date), DATEPART(MONTH, Closing_Date), Category;
    

    It really depends what your desired output is. (Closing Year is not necessary in your example, but if the date range crosses a year boundary it may be).

    回答2

    SQL Server 2012 version above,

    SELECT  format(Closing_Date,'yyyy-MM') as ClosingMonth,
            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 format(Closing_Date,'yyyy-MM'), Category;
    
  • 相关阅读:
    2.2 图像分类-线性分类
    2.1 图像分类-K最近邻算法
    2 图像分类-数据驱动方法
    Week6
    R-CNN 原理详解
    1.2 课程介绍-课程后勤
    012_04Thread+Handler实例应用之号码归属地查询
    010_04用户登录(用户名,密码交给服务器并验证)
    010_03HTML源码查看器
    010_02带缓存的图片查看器
  • 原文地址:https://www.cnblogs.com/chucklu/p/14821412.html
Copyright © 2011-2022 走看看