简体   繁体   中英

How to order all values in group_concat ?

Query:-

SELECT emp.emp_id AS employeeId,
       emp.emp_name AS employeeName,
       **group_concat(CASE
                          WHEN log_date = log_date THEN log_time
                          ELSE ''
                      END) AS logTimings**,
                                         shift AS shift
FROM at_hr_logs_Jan l,
     at_hr_emp employee,
     at_dates dt
WHERE user_id=00000247
  AND l.user_id=emp.emp_code
  AND emp.dept_id=1
  AND l.status_id=fn_getcodevalue_id('STS', 'ACTIVE')
  AND l.log_date=dt.att_date
GROUP BY l.log_date ;

Actual oupput:-

Employee Id  Employee Name Log Timings

00000247  M. Rama Rao  18:03,17:40,13:35,11:48,09:19

00000247  M. Rama Rao  15:24,09:11,18:44,16:37,15:27,15:24

But need:

Employee Id  Employee Name Log Timings

00000247  M. Rama Rao  09:19,11:48,13:35,17:40,18:03

00000247  M. Rama Rao  09:11,15:27,15:24,15:24,16:37,18:44

You can add ORDER BY inside your GROUP_CONCAT .

I don't understand the logic of WHEN log_date = log_date , it will always be true . Then, there is no point of having CASE statement and it won't fall into ELSE case.

 group_concat(CASE WHEN log_date = log_date THEN log_time ELSE '' END)

and

group_concat(log_time)

Both will give you same result. So, you should do following changes

group_concat(log_time ORDER BY log_time) AS logTimings

Notes:

  • Never use commas in the FROM clause. Always use proper, explicit JOIN syntax.
  • Your are aggregating by log_date , so the case EXPRESSION is not needed in the group_concat() .
  • The best practice is to put all non-aggregated columns in the GROUP BY .
  • I would recommend including the date and shift in the SELECT as well.
  • The table alias for the at_hr_emp is employee (in your code) but it is referenced as emp . Just use the abbreviation e .

Hence, this query should be written as:

SELECT e.emp_id AS employeeId, e.emp_name AS employeeName, l.log_date,
       group_concat(log_time order by log_time) as logTimings,
       shift AS shift
FROM at_hr_logs_Jan l JOIN
     at_hr_emp e
     ON l.user_id = e.emp_code JOIN
     at_dates dt
     ON l.log_date = dt.att_date
WHERE e.user_id=00000247 AND e.dept_id = 1 AND
      l.status_id = fn_getcodevalue_id('STS', 'ACTIVE')
GROUP BY e.emp_id, e.emp_name, l.log_date, shift;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM