如何扣除有条件的小时数

时间:2011-02-03 09:37:57

标签: sql sql-server sql-server-2005

使用SQL Server

表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

我想扣除总时间> 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-Breaktime),它会给出类似“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)

如何查询上述情况。

需要查询帮助

3 个答案:

答案 0 :(得分: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)
  评估条件列表和   返回多个可能的一个   结果表达式。

答案 1 :(得分:1)

如果您的数据类型不是datetime且是nvarchar,请参阅此回复:

How to generate the date

答案 2 :(得分: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 @newTotalTime=@Totaltime;
    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]