SELECT datetime AS 'FECHA', IF (type='renew',IF(s.borrowernumber=s.user,'En linea',branch),branch) AS 'SEDE', type AS 'TRANSACCIÓN', i.barcode AS 'ITEM - CODIGO DE BARRAS', i.itype AS 'TIPO DE ITEM', i.ccode as 'SUBTIPO DE ITEM', b.cardnumber AS 'ID USUARIO', s.itemnumber AS 'ITEM NUMBER', concat(b.surname,' ',b.firstname) AS 'USUARIO', b.categorycode AS 'PERFIL', concat(bs.surname,' ',bs.firstname) AS 'STAFF', IF(s.borrowernumber=s.user,'En linea',IF((s.user IS NULL OR s.user=' ') AND branch IS NULL,'En línea APP',IF(bs.borrowernumber IN ("27184","27182","27178","26959","27179","27183","27180","56616"),'Maquina','En sede'))) AS 'MEDIO DE TRANSACCIÓN' FROM ( ( select * from statistics left join action_logs ON (timestamp BETWEEN datetime - INTERVAL 1 SECOND AND datetime + INTERVAL 1 SECOND and itemnumber=object) where date(datetime) BETWEEN <> AND <> and type IN ('renew','localuse') UNION select * from statistics left join action_logs ON (timestamp BETWEEN datetime - INTERVAL 1 SECOND AND datetime + INTERVAL 1 SECOND and borrowernumber=object and action=type) WHERE date(datetime) BETWEEN <> AND <> and type NOT IN ('renew','localuse')) s ) LEFT JOIN borrowers b ON (s.borrowernumber=b.borrowernumber) LEFT JOIN borrowers bs ON (s.user=bs.borrowernumber) LEFT JOIN items i ON (s.itemnumber = i.itemnumber) LEFT JOIN borrower_attributes ba ON (b.borrowernumber = ba.borrowernumber AND code = 'AREA' COLLATE utf8mb4_unicode_ci) GROUP BY datetime, type, i.barcode