这是我的版本,看起来一团糟,但为你的价值观工作:
SELECT l.ID AS LunchID
, ISNULL(DATEDIFF(mi,
CASE WHEN l.StartDate BETWEEN h.StartDate AND h.EndDate THEN l.StartDate ELSE
(CASE WHEN l.StartDate < h.StartDate THEN h.StartDate ELSE NULL END) END,
CASE WHEN l.EndDate BETWEEN h.StartDate AND h.EndDate THEN l.EndDate ELSE
(CASE WHEN l.EndDate > h.EndDate THEN h.EndDate ELSE NULL END) END),
0) AS Result
FROM Lunch l
LEFT JOIN HE h ON h.ID = 1
或者,如果您要在一个查询中更多地使用它,可能会更好地创建一个函数
CREATE FUNCTION GetBetweenMinutes(
@HStart DATETIME,
@HEnd DATETIME,
@LStart DATETIME,
@LEnd DATETIME)
RETURNS INT
AS
BEGIN
DECLARE @DiffStart DATETIME
DECLARE @DiffEnd DATETIME
IF (@LStart BETWEEN @HStart AND @HEnd)
SET @DiffStart = @LStart
ELSE
BEGIN
IF (@LStart < @HStart)
SET @DiffStart = @HStart
ELSE
SET @DiffStart = NULL
END
IF (@LEnd BETWEEN @HStart AND @HEnd)
SET @DiffEnd = @LEnd
ELSE
BEGIN
IF (@LEnd > @HEnd)
SET @DiffEnd = @HEnd
ELSE
SET @DiffEnd = NULL
END
RETURN ISNULL(DATEDIFF(mi,@DiffStart,@DiffEnd),0)
END;
这是带有数据示例的SQL Fiddle