Sql-server – How to sum data over 3 month ranges

sql serversql-server-2008

I have a report where I need to add totals for a column and group them by company selected. I have to do this in T-SQL for 4 ranges:
0-3 Months, 3-6 months, 6-12 months, >12 months
I am confused about how this would be implemented in T-SQL.
There is a balance column on which I have to total.
The problem I am not able to understand is summary over those date ranges. How can this be done in T-SQL?

The user should input the company choice and a date and based on it, I have to generate summary of balance column within the ranges specified, which were
0-3 Months, 3-6 months, 6-12 months, >12 months

I am thinking of it this way: I am thinking of it this way:
Make ranges of date, so : suppose @date is user selected date
then:

DECLARE @daterange1start DATE = @date
DECLARE @daterange1end DATE = (SELECT DATEADD(m,3,@daterange1start))
DECLARE @daterange2start DATE = @daterange1end
DECLARE @daterange2end DATE = (SELECT DATEADD(m,3,@daterange2start))
DECLARE @daterange3start DATE = @daterange2end
DECLARE @daterange3end DATE = (SELECT DATEADD(m,6,@daterange3start)) '

And then using case

SUM (CASE WHEN  dueDate BETWEEN @daterange1start AND @daterange1end THEN    Balance ELSE 0 END) AS '0-3 Months', 
SUM (CASE WHEN dueDate BETWEEN @daterange2start AND @daterange2end THEN Balance ELSE 0 END) AS '3-6 Months',
SUM (CASE WHEN dueDate BETWEEN @daterange3start AND @daterange3end THEN Balance ELSE 0 END) AS '6-12 Months''

Am I thinking of it the right way in terms of a correct solution?

Thank you.

Best Answer

You could categorise your dueDate values and then use PIVOT like this:

WITH categorised AS (
  SELECT
    Balance,
    Range = CASE
      WHEN dueDate < DATEADD(MONTH,  3, @Date) THEN '0-3 Months'
      WHEN dueDate < DATEADD(MONTH,  6, @Date) THEN '3-6 Months'
      WHEN dueDate < DATEADD(MONTH, 12, @Date) THEN '6-12 Months'
      ELSE '>12 Months'
    END
  FROM
    dbo.YourTable
  WHERE
    Company = @Company
    AND dueDate >= @Date
)
SELECT
  [0-3 Months],
  [3-6 Months],
  [6-12 Months],
  [>12 Months]
FROM
  categorised
PIVOT
  (
    SUM(Balance)
    FOR Range IN ([0-3 Months], [3-6 Months], [6-12 Months], [>12 Months])
  ) AS p
;