我正在尝试在给定的表上实现单个视图:
Table:LeaseLog
------------------------------------------------------------------------------------
action license timeStamp
------------------------------------------------------------------------------------
Lease ----YYB-------- 2014-07-18 14:30:36.000 <br/>
Release --YYB-------- 2014-07-18 15:17:11.000 <br/>
Lease ----AAR-------- 2014-07-18 14:40:23.000 <br/>
Release ---AAR ------- 2014-07-18 15:38:41.000 <br/>
Lease ---AAR---------- 2014-07-18 15:41:16.000 <br/>
Lease ---YYB---------- 2014-07-19 07:53:06.000 <br/>
Release ----YYB------ 2014-07-19 08:07:51.000 <br/>
Lease ----YYB--------- 2014-07-19 08:12:43.000 <br/>
Release ----AAR------ 2014-07-19 08:19:59.000 <br/>
目标是在租约和发布时间之间以小时或分钟为单位查找每个已使用许可证的许可证利用率。
i对于每个许可证密钥:通过租赁和释放进行迭代:ConvertIntoHours(LeaseTimeStamp - ReleaseTimeStamp)
ii)按许可证分组(i的结果)
输出应该是这样的:
license TotalUtilzation(Hours)
----------------------------------------------
YYB --------- 160.20 <br/>
AAR ---------- 380 <br/>
我设法编写脚本,使用以下脚本为给定日期时间提供租用和发布的总小时数
SELECT x.license,
SUM(CASE WHEN action='lease' THEN ((DATEPART(hh,timeStamp)*60)+DATEPART(mi,timeStamp)+(DATEPART(ss,timeStamp)/(60.0))) ELSE 0 END)/60.0 as Lease,
SUM(CASE WHEN action='release'THEN ((DATEPART(hh,timeStamp)*60)+DATEPART(mi,timeStamp)+(DATEPART(ss,timeStamp)/(60.0))) ELSE 0 END)/60.0 as Release
FROM [RxDatabase].[dbo].[LeaseLog]AS x
GROUP BY license
我知道这并没有给出正确的结果。
感谢任何帮助。
答案 0 :(得分:1)
因为你需要在两个不同的 ROWS 之间进行计算,你需要使用 OVER 关键字
简而言之:
特定车辆租赁和发布日期之间差异的基本演示
SELECT *, DATEDIFF(hour, leaseTime, releaseTime) AS diff
FROM
(
SELECT x.license, x.action, x.timeStamp as leaseTime
LEAD (x.timeStamp) OVER (ORDER BY x.timeStamp) releaseTime
FROM [RxDatabase].[dbo].[LeaseLog] AS x
WHERE x.license = '----YYB--------'
)