GROUP_CONCAT没有合并字段

时间:2012-09-24 18:34:14

标签: mysql

我使用GROUP_CONTACT时遇到语法问题。

使用如下所示的sql语句:

SELECT 

     s.school_code
    , s.school_name
    ,st.subject
    ,sg.subgroup
    ,GROUP_CONCAT(IF(r.year=2012,a.proficiency_index,NULL)) AS pi_2012
    ,GROUP_CONCAT(IF(r.year=2013,a.proficiency_index,NULL)) AS pi_2013

FROM 
    ayp_data a
        INNER JOIN 
            report_year r ON
                a.report_year_id = r.id
        INNER JOIN
            school s ON
                a.school_code_id = s.id
        INNER JOIN
            sub_group sg ON
                a.subgroup_id = sg.id
        INNER JOIN
            `subject` st ON
                a.subject_id = st.id

GROUP BY
      report_year_id,
      s.school_code
    , s.school_name
    ,st.subject
    ,sg.subgroup
HAVING 
s.school_name = 'Moody Elementary School' AND 
`subject` = 'Mathematics' AND 
`subgroup` = 'All Students'

我得到的结果如下:

SCHOOL_CODE     SCHOOL_NAME     SUBJECT     SUBGROUP    PI_2012     PI_2013
0065    Moody Elementary School     Mathematics     All Students    9.640000343322754   (null)
0065    Moody Elementary School     Mathematics     All Students    (null)  10.920000076293945

我想将两行合并为一行,并将非空字段值PI_2012和PI_2013放在同一行。

思考我可以用GROUP_CONTACT做到这一点;但它并没有像我想象的那样。

我如何使用GROUP_CONCAT合并这些字段?

或者,有更聪明的方法吗?

我有完整的架构和查询here on SQL Fiddle

1 个答案:

答案 0 :(得分:1)

如果您不希望单独的年份出现在单独的行中,则需要从report_year_id子句中删除GROUP BY。那就是 - 你需要改变这个:

GROUP BY
      report_year_id,
      s.school_code
    , s.school_name
    ,st.subject
    ,sg.subgroup

到此:

GROUP BY
      s.school_code
    , s.school_name
    ,st.subject
    ,sg.subgroup