Question

I have a query which brings back the count of rows (distinct child_name) for the period of one month. I would like to write a query so I can bring back a total for multiple months. I would like the to be be able to select a time range and have the months in the range I select automatic calculate without hard coding for each month. I read some info on loops and sequences but I found it hard to understand.

DECLARE @From_DT DATE = '2012-07-01', @To_DT DATE = '2013-7-30';

SELECT count(Child_Name) as July12_Count
FROM ECMS_BACKUP.dbo.vw_B2H_CLIENTS
WHERE CLT_NBR IN (SELECT CLT_NBR FROM ECMS_BACKUP.dbo.ufn_B2H_Enrolled_Clients_List(@From_DT,  @To_DT))

I would like a result like the below without hard coding.

If I were to select:

 DECLARE @From_DT DATE = '2012-07-01', @To_DT DATE = '2013-10-31';

I would get this:

July12_Count  Aug13_Count  Sep13_Count  Oct13_Count  

251           255          250          245

Any feedback is appreciated!

Was it helpful?

Solution

I have to assume that one of the columns in vw_B2H_CLIENTS is the date you are filtering by.

In this case, you could try using DATEPART in order to group by the month (replacing DATE_COL by your date column), as so:

SELECT DATEPART(month, DATE_COL) AS Month,
       COUNT(*) AS Count
  FROM ECMS_BACKUP.dbo.vw_B2H_CLIENTS
  WHERE CLT_NBR IN (SELECT CLT_NBR FROM ECMS_BACKUP.dbo.ufn_B2H_Enrolled_Clients_List(@From_DT, @To_DT))
  GROUP BY DATEPART(month, DATE_COL)

Also note that you may have an error in ufn_B2H_Enrolled_Clients_List as you have @From_DT as the parameter twice (you may want @To_DT).

This would give you output like this:

Month   Count
7       251
8       255
9       250
10      245
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top