簡體   English   中英

每個時間段和用戶只返回一行聚合函數

[英]Returning only one row for an aggregate function per a time period and user

我正在使用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,按聚合列分區並按其排序。 這只返回一行。

一個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

我希望這個能幫上忙

   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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM