我有一个名为rjs_attendance的表,后面有四列
_________________________________________________
|attenedance_id | admin_id | note | created_date|
-------------------------------------------------
用户可以在一天内多次出席。奇数输入被假定为登录,甚至输入被假定为退出。 我需要的输出看起来像这样。
_______________________________________________________________________________
|admin_id | time_in | time_in_note | time_out | time_out_note | date |
-------------------------------------------------------------------------------
|1 |10:00 | none | 11:00 | none | 2015-12-24|
-------------------------------------------------------------------------------
|1 |11:30 |none |12:15 |none | 2015-12-24|
-------------------------------------------------------------------------------
我无法获取同一日期的所有记录,但我能够记录同一日期的一条记录。 我运行的查询如下:
SELECT
`atd_in`.`admin_id` AS `admin_id`,
CAST(MIN(`atd_in`.`created_date`) AS TIME) AS `time_in`,
`atd_in`.`note` AS `time_in_note`,
CAST(MAX(`atd_out`.`created_date`) AS TIME) AS `time_out`,
`atd_out`.`note` AS `time_out_note`,
CAST(`atd_in`.`created_date` AS DATE) AS `date_on`
FROM
`zf2`.`rjs_attendance` `atd_in`
LEFT JOIN `zf2`.`rjs_attendance` `atd_out`
ON
`atd_in`.`admin_id` = `atd_out`.`admin_id`
AND CAST(`atd_in`.`created_date` AS DATE) = CAST(`atd_out`.`created_date` AS DATE)
AND `atd_in`.`attendance_id` <> `atd_out`.`attendance_id`
GROUP BY
CAST(`atd_in`.`created_date` AS DATE), `atd_in`.`admin_id`
非常感谢任何帮助。
答案 0 :(得分:3)
试试这个:
SELECT A.admin_id,
MAX(IF(A.ID % 2 = 1, CAST(A.created_date AS TIME), NULL)) AS time_in,
MAX(IF(A.ID % 2 = 1, note, NULL)) AS time_in_note,
MAX(IF(A.ID % 2 = 0, CAST(A.created_date AS TIME), NULL)) AS time_out,
MAX(IF(A.ID % 2 = 0, note, NULL)) AS time_out_note,
CAST(A.created_date AS DATE) AS date_on
FROM (SELECT IF(@adminId=@adminId:=A.admin_id, @id:=@id+1, @id:=1) AS ID,
A.admin_id, A.note, A.created_date
FROM zf2.rjs_attendance A, (SELECT @id:=1, @adminId:=0) AS B
ORDER BY A.admin_id, A.attendance_id
) AS A
GROUP BY A.admin_id, CAST(A.created_date AS DATE), CEILING(A.ID / 2);
答案 1 :(得分:1)
在看到任何代码之前 - 如果你假设奇数,甚至作为进入和退出=&gt;加入这个条件 -
on A.id +1 = B.id
或
`atd_in`.`attendance_id` +1 = `atd_out`.`attendance_id`
您甚至可以将其保留为非退出条目 (当然,ID应该是数字的)
如果您的记录没有按照这种方式排序,只需在使用order by排序后重新发出id列并创建新的id列