我想从MySQL表中导出特定月份的数据(基于用户输入),我不想计算当月每天的created_at之间的差异。
attendance_id:
当用户上班时,他的入口记录为1(到达),当他离开工作时,他的出口被记录为2(到达)。 用户也可以在家工作,当他们开始工作时,当他们停止记录为2(退出)时,记录为10(在家工作)。 表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.
答案 0 :(得分:0)
如果排除错误并且操作顺序始终为1-2,并且它在同一天出现和解决,我的解决方案是:
SELECT A.user_id, A.created_at,HOUR(TIMEDIFF(B.created_at,A.created_at))
FROM user_attendance A, user_attendance B
WHERE
A.attendance_id in (1,10) AND
B.attendance_id=2 AND
A.user_id=45 AND
B.user_id=A.user_id AND
DAY(A.created_at)=DAY(B.created_at) AND
MONTH(A.created_at)=5
ORDER BY date(A.created_at) ASC
答案 1 :(得分:0)
select ua.day(a.created_at) as day,ua.user_id, HOUR(timediff(max(created_at),min(created_at))) as TimeDiff
from user_attendance ua
where ua.created_at between '2015-05-01 00:00:00' and '2015-05-31 23:59:59'
group by day(ua.created_at),ua.user_id
order by ua.user_id