我想从MySQL表中导出特定月份(基于用户输入)的数据,我不想计算当月每天的created_at之间的差异。根据类型计算每月中每天的行之间的差异
attendance_id:
- 1 =到来
- 2 =出口
- 10 =从家里
当用户开始工作他的入口被记录为1(到达)当他离开工作时,他的出口记录为2(到达)。 用户也可以在家中工作,当他们开始将其记录为10(在家工作)时,他们停止记录为2(退出)。 表user_attendance
+-----+---------+---------------+----------------+----------------+
| id | user_id | attendance_id | created_at | updated_at |
+-----+---------+---------------+----------------+----------------+
| 52 | 45 | 1 | 1.4.2015 6:48 | 1.4.2015 6:48 |
| 53 | 31 | 1 | 1.4.2015 6:52 | 1.4.2015 6:52 |
| 132 | 45 | 2 | 1.4.2015 13:58 | 1.4.2015 13:58 |
| 133 | 31 | 2 | 1.4.2015 14:32 | 1.4.2015 14:32 |
| 159 | 45 | 1 | 2.4.2015 6:49 | 2.4.2015 6:49 |
| 160 | 31 | 1 | 2.4.2015 6:52 | 2.4.2015 6:52 |
| 232 | 31 | 2 | 2.4.2015 15:06 | 2.4.2015 15:06 |
| 233 | 45 | 2 | 2.4.2015 15:09 | 2.4.2015 15:09 |
| 252 | 74 | 10 | 3.4.2015 6:52 | 3.4.2015 6:52 |
| 253 | 74 | 2 | 3.4.2015 15:52 | 3.4.2015 15:52 |
+-----+---------+---------------+----------------+----------------+
SQL:
CREATE TABLE IF NOT EXISTS `user_attendance` (
`id` int(11) NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`attendance_id` int(10) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2836 ;
我尝试:
SELECT A.user_id, A.created_at,HOUR(TIMEDIFF(B.created_at,A.created_at)) AS timedifference
FROM user_attendance A CROSS JOIN user_attendance B
WHERE B.id IN (SELECT MIN(C.id) FROM user_attendance C WHERE C.id > A.id) and A.user_id=45 and A.attendance_id in(1,2) and MONTH(A.created_at)=5
ORDER BY date(A.created_at) ASC
正如你可以看到我有它仅限于特定的用户和两种类型(到达和出口),但结果不正确,因为时差是0.
我希望你已经有了一个可以在数据也是如此,因为样本数据是针对4月份的,但是您在查询中设置了5月份 –
是的,我有抱歉的“错误”示例数据。 – SuperManSL