gpt4 book ai didi

sql - 每个时间段和用户只为聚合函数返回一行

转载 作者:行者123 更新时间:2023-12-02 03:41:58 24 4
gpt4 key购买 nike

我正在使用 SQL Server 2008。

我有如下构造的表:

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

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

所以我有一个聚合函数,它以秒为单位计算 TimeOut 和 TimeIn 之间的 datediff,别名为 Total

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

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

等等

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

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

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

我知道我必须以某种方式使用 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

关于sql - 每个时间段和用户只为聚合函数返回一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com