MySQL使用Codeigniter中的CrossTab将行转换为列

时间:2013-07-27 09:49:02

标签: mysql codeigniter crosstab

正如我在下面尝试但无法完成工作。 我有桌子,包含不同日子的现在学生的出席情况。我知道它需要交叉表查询,如下所示。特别是我想在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” 我不知道查询是否正常。请给出一些指示。感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

选中此内容后,您的查询中似乎缺少引号

这是工作版本:

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;