Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
select cal.months,Count(enqno) As Enquiry
From #Calender cal
Left Outer Join Enquiry e
On Month(cal.months)=Month([Enquiry date])
Where
([Enquiry date]<=Convert(DATETIME,cal.Months))AND
([Enquiry date]>=Convert(DATETIME,cal.Months))OR
([Enquiry date]IS NULL)
Group By cal.Months;
Posted
Updated 8-Oct-14 20:40pm
v2

I would change my #Calendar to have Month and Year fields (int) instead of a datetime. Then join the DatePart(MONTH,[Enquiry Date] = cal.Month and DATEPART(YEAR,[Enquiry Date]) = cal.Year.

I would also rename all my fields to remove the spaces to remove the requirement of [] around every field.
 
Share this answer
 
you can do it in this way:-

Create a temp table that will have all the months between required dates and each record will have count=0
Then Have another Temp Table with available months and count
Apply left join to get required Data
SQL
WITH cte
AS (
	SELECT
		dt = DATEADD(DAY, -(DAY(@StartDate) - 1), @StartDate)

	UNION ALL

	SELECT
		DATEADD(MONTH, 1, dt)
	FROM
		cte
	WHERE
		dt < DATEADD(DAY, -(DAY(@EndDate) - 1), @EndDate))
SELECT
	CONVERT(char(3), dt, 100) + '/' + CONVERT(char(4), dt, 120) AS [month],
	CAST(0 AS decimal) AS Eqcount
INTO
	#AllMonthsData
FROM
	cte;

SELECT
	CONVERT(char(3), [Enquiry date], 100) + '/' + CONVERT(char(4), [Enquiry date], 120) AS [month],
	COUNT(enqno) AS Eqcount
INTO
	#AllAvailableEnquires
FROM
	Enquiry e
WHERE
	([Enquiry date] <= @StartDate)
	AND ([Enquiry date] >= @EndDate)
GROUP BY
	CONVERT(char(3), [Enquiry date], 100) + '/' + CONVERT(char(4), [Enquiry date], 120);

SELECT
	AMD.month,
	ISNULL(A.Eqcount,AMD.Eqcount) AS EqCount
FROM
	#AllMonthsData AMD
	LEFT JOIN #AllAvailableEnquires A ON AMD.month = A.month;

DROP TABLE #AllMonthsData;
DROP TABLE #AllAvailableEnquires;
 
Share this answer
 
v2
SQL
SELECT cal.Months, COUNT(enqno) AS Enquiries
FROM #calendar cal
 LEFT JOIN enquiry
ON Month(cal.Months) = Month([enquiry date])
WHERE (YEAR([enquiry date])=YEAR(GetDate())) OR [enquiry date] IS NULL
GROUP BY cal.Months
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900