当我尝试以下但无法正常工作时。我有一张表,其中包含不同日期在校学生的出勤情况。我知道这将需要交叉表查询,如下所示。特别是我想在 Codeigniter 中做到这一点。
att_2_2013
| student_id| att_date |
-----+-----+----------+-----+-----
| 1 | 2013-07-10|
| 2 | 2013-07-10|
| 3 | 2013-07-10|
| 1 | 2013-07-11|
| 2 | 2013-07-11|
| 4 | 2013-07-11|
| 2 | 2013-07-12|
| 3 | 2013-07-12|
| 4 | 2013-07-12|
| 1 | 2013-07-13|
| 3 | 2013-07-13|
| 4 | 2013-07-13|
我希望它的结果是:
attendance TABLE
| student_id| 2013-07-10 |2013-07-11|2013-07-12|2013-07-13
-----+-----+----------+-----+----------+-----+----------+-----+-----
| 1 | P |P | P| A
| 2 | P |P | A| P
| 3 | A |P | P| P
| 4 | P |A | P| P
我试过这个:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(`att_date` = "', `att_date`,'","P","A")) AS ', `att_date`)
) INTO @sql
FROM att_2_2013;
SET @sql = CONCAT('SELECT student_id, ', @sql, '
FROM att_2_2013
GROUP BY student_id');
SELECT @sql;
它生成查询:
SELECT student_id, MAX(IF(`att_date` = "2013-07-24","P","A")) AS "2013-07-24",MAX(IF(`att_date` = "2013-07-25","P","A")) AS "2013-07-25",MAX(IF(`att_date` = "2013-07-10","P","A")) AS "2013-07-10",MAX(IF(`att_date` = "2013-07-11","P","A")) AS "2013-07-11",MAX(IF(`att_date` = "2013-07-12","P","A")) AS "2013-07-12",MAX(IF(`att_date` = "2013-07-15","P","A")) AS "2013-07-15"
FROM att_2_2013
GROUP BY student_id
但这以某种方式给出了这个错误:“字段列表”中的未知列“att_date”我不知道,因为查询很好。请给出一些指示。我感谢您的帮助!