2011-02-03 42 views
-1

使用SQL Server如何扣除小时condtion

表1

ID, MinTime, TotalTime, BreakTime 

001, 04:00:00, 12:00:00, 00:30:00 
002, 04:00:00, 03:00:00, 00:30:00 
003, 08:00:00, 07:30:00, 03:30:00 
004, 04:00:00, 03:59:59, 01:30:00 

我要扣除TOTALTIME,课间时TOTALTIME> mintime

Condtion: 

If Totaltime is greater than mintime then it should deduct the total hours, but it should Maintain the MinTime 

例如:

Min time: 05:00:00 
Total Time: 06:00:00 
BreakTime: 01:30:00 

总时间超过分钟时间越大,所以我们可以做(TOTALTIME,课间) ,它会给出像“04:30:00”这样的输出(不正确,因为它应该保持最短时间,所以它应该从休息时间扣除1小时)

预期输出

ID, MinTime, TotalTime, BreakTime DeductTime 

001, 04:00:00, 12:00:00, 00:30:00 11:30:00 (TotalTime is Greater than mintime) 
002, 04:00:00, 04:35:00, 01:00:00 04:00:00 (`Here TotalTime is greather than mintime, so it should deduct the breaktime from the total hours, but it should maintain the mintime also)` 
003, 08:00:00, 07:30:00, 03:30:00 07:30:00 (TotalTime is less than mintime) 
004, 04:00:00, 03:59:59, 01:30:00 03:59:59 (TotalTime is less than mintime) 

如何查询上述条件。

需要查询帮助

+1

有没有在你的例子一些矛盾选择。在最后三行`TotalTime`小于`MinTime`,但最后一行显示`DeductTime = 04:00:00 = MinTime`,而另外两行`DeductTime = TotalTime`。另外,什么数据类型用于时间值? – 2011-02-03 10:01:05

回答

2

您可以使用CASE声明

SELECT ID 
     , MinTime 
     , TotalTime 
     , BreakTime 
     , CASE WHEN TotalTime < MinTime THEN TotalTime 
       WHEN TotalTime - BreakTime < MinTime THEN MinTime 
       ELSE TotalTime 
      END AS DeductTime 
FROM Table1 

CASE(的Transact-SQL)
评价了条件列表和 返回多个可能 结果的表现之一。

+0

@赖文,感谢您的回复,我修改了我的问题。你可以看看 – Gopal 2011-02-03 11:39:00

+0

@Gopal:我已经编辑了答案,但花费更多的精力找到解决方案本身就会让你长期更好地服务*(这是Lieven顺便说一句,不是活的)*。 – 2011-02-03 13:37:12

0

尝试使用用户定义的函数。

create function GetTotalHours (@BreakTime datetime,@Totaltime datetime, @MinTime DateTime) returns datetime 
as 
begin 
declare @newTotalTime datetime; 
declare @DiffenceInHours int; 
set @DiffenceInHours = datediff(HH,@BreakTime,@Totaltime); 

if @Totaltime >@MinTime 
    begin --If Totaltime is greater than mintime then it should deduct the total hours 
     set @newTotalTime=dateDiff(HH,@DiffenceInHours,@Totaltime); 
    end 
else 
    begin--If totaltime is smaller than mintime then it should not deduct the total hours 
     set @[email protected]; 
    end 

return @newTotalTime ; 
end 
go 

然后从表中使用UDF,这样的事情....

select dbo.GetTotalHours('2011-02-03 14:51:48.620', 
    '2011-02-03 11:51:48.620','2011-02-03 11:51:48.620') 
from [YourSourceTable]