你能帮我解决下面的问题吗?
我的目标:
对于每一天,每位员工选择最短日期时间和最长日期时间,并以分钟为单位获取时差
我的查询:
SELECT
PersonalId, Name, LastName,
Min(TmsPrick) as MinDatetime,
Max(TmsPrick) as MaxDatetime,
DATEDIFF(mi, MIN(TmsPrick), MAX(TmsPrick)) AS Expr1
FROM
prickTable
GROUP BY
DATEPART(dy, TmsPrick), PersonalId, name, lastname, TmsPrick
ORDER BY
PersonalId, TmsPrick
注意: DATEPART(dy,TmsPrick)=一年中的某一天
我的预期输出
PersonalId | Name | LastName | MinDatetime | MaxDatetime | Expr1
------------------------------------------------------------------------------------
000001 | A | AC |2014-01-05 07:12:00|2014-01-05 16:00:00 | 528
000001 | A | AC |2014-01-06 07:08:00|2014-01-05 16:00:00 | 532
000001 | A | AC |2014-01-07 07:11:00|2014-01-07 16:00:00 | 529
000002 | B | BD |2014-01-05 07:11:00|2014-01-05 16:00:00 | 529
我得到的输出:
PersonalId | Name | LastName | MinDatetime | MaxDatetime | Expr1
------------------------------------------------------------------------------------
000001 | A | AC |2014-01-05 07:12:00|2014-01-05 16:00:00 | 1053168
000001 | A | AC |2014-01-06 07:08:00|2014-01-05 16:00:00 | 532
000001 | A | AC |2014-01-07 07:11:00|2014-01-07 16:00:00 | 529
000002 | B | BD |2014-01-05 07:11:00|2014-01-05 16:00:00 | 1053169
知道为什么我的输出显示出这样的差异吗?
由于
注意: Tmsprick中的值可能会从一天中的几个变为一周中的两个。该表包含超过3年的值。
答案 0 :(得分:3)
好吧,如果没有看到源数据,很难确定,但您在MAX
/ MIN
和DATEDIFF
使用了不同的日期列:
SELECT
PersonalId,
Name,
LastName,
Min(TmsPrick) as MinDatetime,
Max(TmsPrick) as MaxDatetime ,
DATEDIFF(mi, MIN(tijdstip), MAX(tijdstip)) AS Expr1
^-- should be TmsPrick?
答案 1 :(得分:1)
我怀疑你想要的查询是:
SELECT PersonalId, Name, LastName,
Min(TmsPrick) as Mintime, Max(TmsPrick) as Maxtime,
DATEDIFF(mi, MIN(TmsPrick), MAX(TmsPrick)) AS Expr1
FROM prickTable
GROUP BY PersonalId, name, lastname, cast(TmsPrick as date)
ORDER BY PersonalId, max(TmsPrick);
这将给出每天“过去”的时间,因为第一个和最后一个“tmsprick”。