我有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之间
答案 0 :(得分:1)
我想你想要这个
SELECT DATEDIFF(mi,End_Date_HE,Start_Date_HE) AS DiffDate
SELECT DATEDIFF(mi,End_Date_Luch,Start_Date_Lunch ) AS DiffDate
答案 1 :(得分: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,其中包含数据样本