8

I have a query that returns expiration dates:

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

The expiration dates can be anytime during any month and any year.

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

I have no idea how I would do this?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
user380432
  • 4,619
  • 16
  • 51
  • 62

2 Answers2

25

You can do something like this:

e.g. how many units are due to expire in 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)
AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
4

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

RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262