当我使用'选择'时,如何将表格中的所有日期都放在新列中?在MySQL?

时间:2016-02-17 03:24:51

标签: mysql

我有一个SQL查询

SELECT
 student.`firstname` AS student_firstname,
 student.`lastname` AS student_lastname,
 DATE_FORMAT(attendance.`date`, '%M %d, %Y') AS attendance_date,
 class.`subcode` AS class_subcode,
 student.`idno` AS student_idno
FROM
 `student` student INNER JOIN `attendance` attendance ON student.`idno` = attendance.`sidno`
 INNER JOIN `class` class ON attendance.`classid` = class.`id`
WHERE
 class.iidno = 930
GROUP BY student.idno
HAVING SUM(attendance.remark='absent') > 3
ORDER BY
 class.subcode,
 student.lastname, 
 attendance.date
ASC

此查询显示所有缺席3次或以上的学生,但在attendance.date字段中,它只显示一个日期。我想显示所有attendance.date

attendance.remark='absent'

这是上面查询的示例显示

student_firstname   student_lastname   attendance_date   class_subcode   student_idno
Student 1 fs        Student 1 ls       February 01, 2016 IT421           0000001
Student 2 fs        Student 2 ls       February 01, 2016 IT421           0000002
Student 3 fs        Student 3 ls       February 01, 2016 IT421           0000003

你可以看到它只包含1个日期,即使该学生有超过3个缺席。我需要这样的显示器

student_firstname   student_lastname   attendance_date   class_subcode   student_idno
Student 1 fs        Student 1 ls       February 01, 2016 IT421           0000001
Student 1 fs        Student 1 ls       February 02, 2016 IT421           0000001
Student 1 fs        Student 1 ls       February 03, 2016 IT421           0000001
Student 2 fs        Student 2 ls       February 01, 2016 IT421           0000002
Student 3 fs        Student 3 ls       February 01, 2016 IT421           0000003
Student 3 fs        Student 3 ls       February 02, 2016 IT421           0000003

或者可能是这样的

student_firstname   student_lastname   attendance_date   class_subcode   student_idno
Student 1 fs        Student 1 ls       Feb 01, Feb 02    IT421           0000001
Student 2 fs        Student 2 ls       Feb 01            IT421           0000002
Student 3 fs        Student 3 ls       Feb 01, Feb 02    IT421           0000003

这可能吗?

1 个答案:

答案 0 :(得分:0)

请尝试以下方法以匹配您的第二个预期结果。

SELECT
 student.`firstname` AS student_firstname,
 student.`lastname` AS student_lastname,
 GROUP_CONCAT(DATE_FORMAT(attendance.`date`, '%b %d') SEPARATOR ', ') AS attendance_date,
 class.`subcode` AS class_subcode,
 student.`idno` AS student_idno
FROM
 `student` student INNER JOIN `attendance` attendance ON student.`idno` = attendance.`sidno`
 INNER JOIN `class` class ON attendance.`classid` = class.`id`
WHERE
 class.iidno = 930
GROUP BY student.idno
HAVING SUM(attendance.remark='absent') > 3
ORDER BY
 class.subcode,
 student.lastname, 
 attendance.date
ASC