programing

MySQL은 단일 행에서와 같이 최소 열과 최대 열에 대해 일치하는 행을 가져옵니다.

prostudy 2022. 9. 14. 21:25
반응형

MySQL은 단일 행에서와 같이 최소 열과 최대 열에 대해 일치하는 행을 가져옵니다.

안녕하세요 전문가 여러분! 저는 아래와 같은 타임시트 표를 가지고 있습니다.

타임시트 테이블

+-------------------------------------------+
|employee_no    |time             |device_id|
+-------------------------------------------+
|1              |2019-09-17 07:00 |001      |
|1              |2019-09-17 14:00 |002      |
|2              |2019-09-19 08:00 |002      |
|2              |2019-09-20 15:00 |003      |
+-------------------------------------------+

직원들의 출입 시간을 파악하기 위해 다음 쿼리를 사용하고 있습니다.

select  timesheets.employee_no, 
        MIN(time) as in_time, 
        MAX(time) as out_time, 
        COUNT(`time`) as record_count
from timesheets 
where `time` between '2019-09-17 00:00:00' 
                      and '2019-09-17 23:59:59' 
group by timesheets.employee_no

아래와 같이 원하는 출력을 얻을 수 있습니다.

+----------------------------------------------------------------+
|employee_no    |in_time          |out_time         |record_count|
+----------------------------------------------------------------+
|1              |2019-09-17 07:00 |2019-09-17 14:00 |2           |
|2              |2019-09-19 08:00 |2019-09-20 15:00 |2           |
+---------------------------------------------------+------------+

이제 입력 및 출력 레코드의 device_id를 취득해야 합니다.time_in_device_id그리고.time_out_device_id어떻게 그것을 달성할 것인가?

사용 안 함between시간이 지남에 따라.다음은 더 간단하고 정확합니다.

MySQL은 "first()" 및 "last()" 집계 함수를 제공하지 않습니다.단, 문자열 조작을 사용하여 원하는 작업을 수행할 수 있습니다.

select ts.employee_no, 
       MIN(time) as in_time, 
       MAX(time) as out_time, 
       COUNT(time) as record_count,
       SUBSTRING_INDEX(GROUP_CONCAT(device_id ORDER BY time), ',', 1) as first_device_id,
       SUBSTRING_INDEX(GROUP_CONCAT(device_id ORDER BY time DESC), ',', 1) as lasst_device_id
from timesheets ts
where `time` >= '2019-09-17' and
      `time` < '2019-09-18' 
group by ts.employee_no

서브쿼리를 사용하다

select a.*,b.deviceid as indeviceid,b1.deviceid as outdeviceid from
    (
    select  timesheets.employee_no, MIN(time) as in_time, MAX(time) as out_time, COUNT(`time`) as record_count
     from timesheets 
     where `time` between '2019-09-17 00:00:00' and '2019-09-17 23:59:59' group by timesheets.employee_no
    ) a join timesheets b on a.in_time=b.time
      join timesheets b1 a.out_time=b1.time

언급URL : https://stackoverflow.com/questions/58115097/mysql-get-the-matching-rows-for-the-min-and-max-columns-as-in-a-single-row

반응형