我已经编写了下面的代码,我想返回一个pqpageId,日期和小时,它具有最小计数。 提前谢谢。
代码:
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 NCPI.RequestDateTime between dateadd(hour, -1, getdate()) and getdate()
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
Output :
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
2 04-11-2015 9 10
2 11-11-2015 9 56
但我期待
PQPageId ||日期||小时|| MINCOUNT
1 09-11-2015 8 54
2 04-11-2015 9 10
答案 0 :(得分:0)
您可以尝试以下代码:
WITH CTE AS (...)
SELECT PQPageId, Date, HOUR, HourlyPQPageIdCount AS MINCOUNT
FROM (
SELECT PQPageId, Date, HOUR, HourlyPQPageIdCount
RANK() OVER(PARTITION BY HOUR ORDER BY HourlyPQPageIdCount) AS r
FROM CTE WITH (NOLOCK) ) A
WHERE r = 1