0

我有 4 个约会。例如。

2 个开始日期和 2 个结束日期,例如:

Start_Date_HE 2013-08-15 01:24:00.000   

End_Date_HE 2013-08-15 02:09:00.000

Start_Date_Lunch    
2013-08-14 20:40:00.000 

End_Date_Luch
2013-08-14 21:40:00.000

我想知道这些日期之间我有多少分钟。

在此示例中可能为 0。因为 20:40 到 21:40 不在 01:24 到 02:09 之间

4

2 回答 2

1

我想你想要这个

SELECT DATEDIFF(mi,End_Date_HE,Start_Date_HE) AS DiffDate

SELECT DATEDIFF(mi,End_Date_Luch,Start_Date_Lunch ) AS DiffDate
于 2013-08-19T16:27:17.920 回答
0

这是我的版本,看起来一团糟,但为你的价值观工作:

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

于 2013-08-19T17:57:52.267 回答