3

我正在使用 SQL Server 2008。

我的表格按以下方式构建:

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

我想要的结果是:对于第 7 小时(上午 7 点)和第 18 小时(下午 6 点)之间的每一个小时,我想知道最高的用户(TimeIn-TimeOut每个位置-最后一个条件是可选的-

所以我有一个聚合函数来计算datediffTimeOut 和 TimeIn 之间的秒数,别名为 Total

我希望我的结果看起来有点像这样:

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

等等

到目前为止我已经尝试过:

使用该ROW_NUMBER()函数的 CTE,按我的聚合列分区并按它排序。这只返回一行。

一个 CTE,我在其中进行所有聚合(包括datepart(hour,date))并使用max聚合在我的外部查询中获得最高的总时间。

我知道我必须以某种方式使用 CTE,我只是不确定如何加入 cte 和我的外部查询。

我在正确的轨道上使用ROW_NUMBER()orRank()吗?

我试过的查询:

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
4

1 回答 1

1

我希望这个能帮上忙

   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
于 2013-10-23T15:03:19.367 回答