This is the code I have written and I am trying to retrieve minimum count of PQpageId for every hour for a given date of range.
WITH CTE AS ( SELECT PQIM.PQPageID ,PQIM.PageURL as PageDescription ,CONVERT(Date,NCPI.RequestDateTime) AS [Date] ,DATEPART(HOUR,NCPI.RequestDateTIme) AS [HOUR] ,ISNULL (COUNT(NCPI.PQPageID),0)AS HourlyPQPageIdCount FROM dbo.NewCarPurchaseInquiries AS NCPI WITH (NOLOCK) RIGHT JOIN dbo.PQPageIds_MasterTblFrom3rdNov2015 AS PQIM WITH (NOLOCK) ON PQIM.PQPageID = NCPI.PQPageId WHERE CONVERT(DATE,NCPI.RequestDateTime) >= '2015-11-04' AND DATEPART(hour,NCPI.RequestDateTime) between 8 and 23 GROUP BY PQIM.PQPageId, CONVERT(Date,NCPI.RequestDateTime), DATEPART(HOUR,NCPI.RequestDateTIme), PQIM.PageURL ) SELECT CT.PQPageId , CT.Date , CT.HOUR, MIN( CT.HourlyPQPageIdCount)AS MINCOUNT FROM CTE CT WITH (NOLOCK) GROUP BY CT.PQPageId , CT.Date , HourlyPQPageIdCount, CT.HOUR ORDER BY MINCOUNT, CT.[HOUR], CT.[Date], PQPageID asc
This is the output I get :
PQPageId Date HOUR MINCOUNT -------- ---------- ---- -------- 1 04-11-2015 8 2359 1 05-11-2015 8 2332 1 06-11-2015 8 2008 1 07-11-2015 8 1964 1 08-11-2015 8 2139 1 09-11-2015 8 54 1 04-11-2015 9 56 1 11-11-2015 9 10 1 11-11-2015 10 4 1 11-11-2015 10 45 2 11-11-2015 8 14 2 11-11-2015 8 10 2 11-11-2015 9 5 2 11-11-2015 9 2 2 11-11-2015 10 2 2 11-11-2015 10 1But I am expecting
PQPageId Date HOUR MINCOUNT -------- ---------- ---- -------- 1 09-11-2015 8 54 1 11-11-2015 9 10 1 11-11-2015 10 4 2 11-11-2015 8 10 2 11-11-2015 9 2 2 11-11-2015 10 1For ex: Pqpageid 1, at 8am on date 4-11-2015 has a count of 2359
and on 9-11-2015
at 8 am it has count 54then it should return date 9-11-2015 and count 54 for hour 8
like wise for every pageid and hour from 8 to 23 it should return the min count from given date of range.