简体   繁体   English

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

[英]MySQL Transform rows to column with CrossTab in Codeigniter

As i tried the below but can't make it out to work. 当我尝试以下内容,但无法正常工作时。 I have table containing attendance of present students on different days. 我有一张桌子,其中包含不同日期的在读学生。 I know it will require crosstab query as below. 我知道它将需要如下交叉表查询。 and especially i wanna do this in Codeigniter. 特别是我想在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|

I want its result to be: 我希望它的结果是:

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

I tried with this: 我尝试了这个:

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;

It generated Query: 它生成查询:

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

But this somehow giving this error: Unknown column ' att_date' in 'field list' I don't know as query is fine. 但这以某种方式给了这个错误:我不知道“字段列表”中的未知列“ att_date”,因为查询很好。 Please give some directions. 请给一些指示。 I appreciate your help! 我感谢您的帮助!

After checking this, Looks like you're missing quotes in your query 经过检查后,看起来您在查询中缺少引号

Here's the working version: 这是工作版本:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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