2013-10-23 73 views
3

我使用SQL Server 2008的返回只有一行,每一個時間段和用戶聚合函數

我有表構造方式如下:

Date (datetime) 
TimeIn (datetime) 
TimeOut (datetime) 
UserReference (nvarchar) 
LocationID 

我想要的結果是:對於每小時7小時(早上7點)和小時18(下午6點)之間的每個小時,我想知道每個位置最高的用戶(TimeIn - TimeOut)。 -last條件是可選 -

所以我有它計算出datediff在超時和TimeIn之間秒的聚合函數別名爲總

我想我的結果看起來有點像這樣:

Hour 7 | K1345 | 50 | Place #5 
Hour 7 | K3456 | 10 | Place #4 
Hour 8 | K3333 | 5 | Place #5 

我試過到目前爲止:使用ROW_NUMBER()功能

的CTE,PA通過我的彙總專欄進行分類並按其排序。這隻返回一行。

一個CTE,我通過我所有的聚合(包括datepart(hour,date))和使用max聚合來獲得我的外部查詢中最高的總時間。

我知道我必須以某種方式使用CTE,我只是不確定如何加入cte和我的外部查詢。

我在正確的軌道上使用ROW_NUMBER()Rank()

查詢我已經試過:

WITH cte as 
(
SELECT * , 
     rn = ROW_NUMBER() over (partition by datediff(second, [TimeIn], [TimeOut])order by datediff(second, [TimeIn], [TimeOut]) desc) 
FROM TimeTable (nolock) 
where DateCreated > '20131023 00:00:00' and DateCreated < '20131023 23:59:00'  
) 
SELECT datepart(hour,cte.DateCreated) as hour,cte.UserReference,(datediff(second, [TimeIn], [TimeOut])) as [Response Time],LocationID 
from cte 
where cte.rn = 1 
and DATEPART(hh,datecreated) >= 7 and DATEPART(hh,datecreated) <= 18 
order by hour asc 

這僅返回幾行

別的東西,我已經試過:

with cte as 
(
SELECT Datecreated as Date, 
     UserReference as [User], 
     datediff(second, [TimeIn], [TimeOut]) as Time, 
     LocationID as Location 
FROM TimeTable 
WHERE datecreated... --daterange 
) 
SELECT DATEPART(HOUR,date), cte.[User], MAX(Time), Location 
FROM cte 
WHERE DATEPART(hh,datecreated) >= 7 and DATEPART(hh,datecreated) <= 18 
GROUP BY DATEPART(HOUR,date), cte.[User], Location 

樣本數據的行

Date     UserRef TimeIn     TimeOut   locationid 
2013-10-23 06:26:12.783 KF34334 2013-10-23 06:27:07.000 2013-10-23 06:27:08.000 10329 
+1

請發佈您已經嘗試過的查詢。 –

+2

另外,請添加幾行樣本數據,從中獲得所需的結果。 –

回答

1

我希望這將是l幫助

WITH TotalTime AS (
     SELECT 
      CAST(DateCreated AS DATE) as [date] 
      ,DATEPART(hour,DateCreated) AS [hour] 
      ,SUM(DATEDIFF(second,TimeIn,TimeOut)) AS Total 
      ,UserReference 
      ,locationid 
     FROM TimeTable 
     GROUP BY UserReference,locationid,CAST(DateCreated AS DATE),DATEPART(hour,DateCreated) 
     HAVING DATEPART(hh,DateCreated) >= 7 and DATEPART(hh,DateCreated) <= 18 
    ) 
    , rn AS (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY [date],[hour],locationid ORDER BY Total DESC) AS row_num 
     FROM TotalTime 
    ) 
    SELECT * 
    FROM rn 
    WHERE row_num = 1 
+0

它的工作,謝謝@ –

相關問題