SQL group dates by month

前端 未结 2 921
予麋鹿
予麋鹿 2021-01-18 04:37

I have a query that returns expiration dates:

    SELECT ci.accountnumber
           , ci.accountname
           , cvu.ExpirationDate
      FROM dbo.clientin         


        
2条回答
  •  一个人的身影
    2021-01-18 04:45

    I need to return counts of how many units are due to expire within each month for a 12 month period.

    If you mean from the current month forward, then

    SELECT
        [YYYY.MM]    = CONVERT(varchar(7), cvu.ExpirationDate, 102),
        CountInMonth = COUNT(*)
    FROM dbo.clientinfo ci
    JOIN clientvehicleunit cvu ON ci.clientid = cvu.clientid
    WHERE cvu.ExpirationDate >= DATEADD(m, DATEDIFF(m,0,getdate()), 0)
      AND cvu.ExpirationDate <  DATEADD(m, DATEDIFF(m,0,getdate())+12, 0)
    GROUP BY CONVERT(varchar(7), cvu.ExpirationDate, 102)
    ORDER BY [YYYY.MM]
    

    Note: The period is printed in the form [YYYY.MM], e.g. 2011.01

提交回复
热议问题