如果差异小于10分钟,如何将日期之间的时间相加

时间:2015-12-13 20:00:39

标签: ios sql database macos core-data

我有模型Activity,我在用户进行某些活动时存储timeInterval / NSDate,可能会出现用户休息15分钟并返回的情况。我想在活动之间加上时间,只要它们之间的差异小于10分钟并测量他的工作实时。我如何创建NSPredicate来实现这一目标?

2 个答案:

答案 0 :(得分:-1)

为你准备好了。我认为这是一个很好的例子。

-- Set Employee ID And Date Required Here
DECLARE @ID INT = 7;
DECLARE @Date SMALLDATETIME = '20150615';

--create our table
DECLARE @TableRows TABLE
(
ID TINYINT,
ActionLog SMALLDATETIME
);

-- Insert some data
INSERT INTO @TableRows
VALUES
(10,'20150615 16:01:00'),
(7,'20150615 16:02:00'),
(7,'20150615 16:04:00'),
(10,'20150615 16:04:00'),
(10,'20150615 16:23:00'),
(10,'20150615 16:25:00'),
(10,'20150615 16:26:00');

-- First CTE for Row Numbers
WITH RowNumCTE
AS
(SELECT 
      ROW_NUMBER() OVER(ORDER BY ActionLog) AS RowNum
    , ActionLog
FROM 
    @TableRows
WHERE
    ID = @ID AND
    datediff(day, @Date, ActionLog) = 0
)

-- SUM of all the Minutes

SELECT 
    SUM(DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog)) as Mins
FROM RowNumCTE t1
    LEFT JOIN RowNumCTE t2 ON T1.RowNum = T2.RowNum + 1
WHERE
    DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog) < 10

答案 1 :(得分:-1)

更好,更快的例子。这使用LEAD窗口函数(在SQL 2012中创建)。

-- Set Required Date Here
DECLARE @Date SMALLDATETIME = '20150615';

--create our table
DECLARE @TableRows TABLE
(
TableID INT IDENTITY(1,1) PRIMARY KEY,
ID TINYINT,
ActionLog SMALLDATETIME
);

-- Insert some data
INSERT INTO @TableRows
VALUES
(10,'20150615 16:01:00'),
(7,'20150615 16:02:00'),
(7,'20150615 16:04:00'),
(10,'20150615 16:04:00'),
(10,'20150615 16:23:00'),
(10,'20150615 16:25:00'),
(10,'20150615 16:26:00');

-- First CTE for Row Numbers (To force the LEAD first in the QEP)
WITH AllMinsCTE
AS
(SELECT 
    ID AS EmployeeID,
    DATEDIFF(MINUTE, ActionLog, LEAD(ActionLog) OVER(PARTITION BY id ORDER BY id, actionlog)) as Mins
FROM 
    @TableRows
WHERE
    datediff(day, @Date, ActionLog) = 0
)

SELECT 
    EmployeeID, 
    SUM(AllMinsCTE.Mins) as Mins FROM AllMinsCTE
WHERE
    AllMinsCTE.Mins < 10
Group BY EmployeeID;