要在mysql中排的列

时间:2012-12-16 20:57:34

标签: mysql sql pivot

我需要帮助从反馈表中收集数据。

我有像

这样的表格

tbl_parent_child_details

fld_parent_id   fld_parent_name  fld_child_name   fld_class   fld_section
1               Tom              Ray               8          A
2               Dev              angelina         12          B 

tbl_feedback_children

fld_parent_id  fld_quetion_id   fld_ans 
1              1                1
1              2                3
1              3                2
2              1                4
2              2                5
2              3                2

tbl_feedback_admini

fld_parent_id  fld_quetion_id   fld_ans 
1              1                1
1              2                3
1              3                2
2              1                4
2              2                5
2              3                2

现在我的要求是我想要一行中每个父母的数据,如:

Parent child q1 q2 q3 q4 q5 q6
tom ray 1 3 2 1 3 2
dev angelina 4 5 2 4 5 2

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

这种类型的操作称为PIVOT,但MySQL没有透视功能,因此您可以使用带有CASE语句的聚合函数来复制它。

您的查询将与此类似:

select pc.fld_parent_name,
  pc.fld_child_name,
  max(case when a.fld_quetion_id = 1 then a.fld_ans end) q1,
  max(case when a.fld_quetion_id = 2 then a.fld_ans end) q2,
  max(case when a.fld_quetion_id = 3 then a.fld_ans end) q3
from tbl_parent_child_details pc
left join tbl_feedback_admini a
  on pc.fld_parent_id = a.fld_parent_id
left join tbl_feedback_children c
  on pc.fld_parent_id = c.fld_parent_id
  and a.fld_quetion_id = c.fld_quetion_id
group by pc.fld_parent_name, pc.fld_child_name

请参阅SQL Fiddle with Demo

如果您要转换已知数量的问题,则上述情况很有效。如果您有未知的数字,那么您可以使用类似于此的准备语句:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when a.fld_quetion_id = ''',
      fld_quetion_id,
      ''' then a.fld_ans end) AS q',
      fld_quetion_id
    )
  ) INTO @sql
FROM tbl_feedback_admini;

SET @sql = CONCAT('SELECT pc.fld_parent_name, 
                    pc.fld_child_name, ', @sql, ' 
                  from tbl_parent_child_details pc
                  left join tbl_feedback_admini a
                    on pc.fld_parent_id = a.fld_parent_id
                  left join tbl_feedback_children c
                    on pc.fld_parent_id = c.fld_parent_id
                    and a.fld_quetion_id = c.fld_quetion_id
                  group by pc.fld_parent_name, pc.fld_child_name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

请参阅SQL Fiddle with Demo

两者都会返回结果:

| FLD_PARENT_NAME | FLD_CHILD_NAME | Q1 | Q2 | Q3 |
---------------------------------------------------
|             Dev |       angelina |  4 |  5 |  2 |
|             Tom |            Ray |  1 |  3 |  2 |