2015-11-23 57 views
-1

我寫下面的代碼,我想返回一個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 ||日期|| HOUR || MINCOUNT

1 2015年9月11日8 54

2 2015年4月11日9 10

+1

歡迎StackOverflow上。請確保你的問題實際上包含一個問題。解釋你的查詢試圖執行的邏輯,而不是期望人們從預期的和實際的輸出中推斷出它。您提供的信息越多,獲得有用答案的機會就越多。 – APC

回答

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