4

我正在处理一张表格,我需要使用以下值计算行程之间的平均时间。

Date        Clockin       CLockout        Trip1           Trip2
====        =======       ========        =====           ======
01/01/2013   13:00        17:00            3               3

我试过这个。

(datediff(minute,[Clockin],[ClockOut])/case when [Trip1]=(0) then NULL else [Trip1] end+case when [Trip2]=(0) then NULL else [Trip2] end)

(datediff(minute,[Clockin],[ClockOut])/case when [Trip1]=(0) then 1 else [Trip1] end+case when [Trip2]=(0) then 1 else [Trip2] end)

目标是计算行程之间的持续时间。即,如果trip2 为空,则为4 小时/ 3 次,否则为4 小时/ 3 + 3(4 小时/ 6 次)

但以上似乎并没有产生正确的结果。

任何帮助将不胜感激。

4

3 回答 3

2

根据您希望如何处理 0 的行程总和(是否为空结果?),以下计算之一应该有效:

declare @t table ([Date] date, Clockin time, CLockout time, Trip1 int, Trip2 int)
insert into @t  

    select '01/01/2013', '13:00', '17:00', 3, 3 union all
    select '01/01/2013', '13:00', '17:00', 0, 3 union all
    select '01/01/2013', '13:00', '17:00', 0, 0 union all
    select '01/01/2013', '13:00', '17:00', 3, null;

select  [minutes]=datediff(mi, Clockin, Clockout), 
        [trips] = ((isnull(Trip1, 0)+isnull(Trip2,0))),
        [calc] = datediff(mi, Clockin, Clockout)/ (nullif((isnull(Trip1, 0)+isnull(Trip2,0)), 0)),
        [calc2] = datediff(mi, Clockin, Clockout)/ isnull((nullif((isnull(Trip1, 0)+isnull(Trip2,0)), 0)), 1)
from @t
于 2013-02-08T07:50:48.917 回答
0
CASE WHEN trip2 IS NULL 
     THEN DATEDIFF(hour,[Clockin],[ClockOut]) / Trip1 
     ELSE (DATEDIFF(hour,[Clockin],[ClockOut]) / Trip1 + Trip2) 
        * (DATEDIFF(hour,[Clockin],[ClockOut]) + (Trip1 + Trip2)) 
END
于 2013-02-08T07:52:42.173 回答
0

尝试这样的事情:

SELECT 
  CONVERT(Decimal, DateDiff(hh,ClockIn,ClockOut)) / 
  CASE 
    WHEN Trip1 IS NULL AND Trip2 IS NULL THEN 1
    ELSE CONVERT(Decimal, (COALESCE(Trip1,0) + COALESCE(Trip1,0)))
  END as result
FROM YourTable

如果 Trip1 和 Trip2 都为 NULL,我不确定您想要什么,但我添加了一个 CASE 语句来除以 1。

这是小提琴

祝你好运。

于 2013-02-08T07:54:06.933 回答