SQL组按月分组

时间:2011-02-24 16:35:17

标签: sql sql-server tsql

我有一个返回到期日期的查询:

    SELECT ci.accountnumber
           , ci.accountname
           , cvu.ExpirationDate
      FROM dbo.clientinfo ci
INNER JOIN clientvehicleunit cvu ON ci.clientid = cvu.clientid

到期日可以是任何月份和任何一年的任何时间。

我需要在12个月内返回每个月内到期的单位数量....

我不知道我会怎么做?

2 个答案:

答案 0 :(得分:17)

您可以这样做:

e.g。有多少单位将于2012年到期:

SELECT MONTH(cvu.ExpirationDate) AS Mnth, YEAR(cvu.ExpirationDate) AS Yr, 
    COUNT(*) AS DueToExpire
FROM clientvehicleunit cvu
WHERE cvu.ExpirationDate >= '20120101' AND cvu.ExpirationDate < '20130101'
GROUP BY MONTH(cvu.ExpirationDate), YEAR(cvu.ExpirationDate)

答案 1 :(得分:1)

  

我需要在12个月内返回每月到期的单位数量。

如果你的意思是从当前月份开始,那么

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]

注意:期间以[YYYY.MM]的形式打印,例如2011.01