CONCAT中的GROUP_CONCAT

时间:2018-11-28 14:44:00

标签: mysql concat group-concat

数据库层次结构如下

  
  • 学生姓名
    • 分配给每个学生的费用清单   学生                 
                        
      • 分配给每项费用的奖学金列表
      •                 

作为结构,预期输出为

学生姓名-费用->奖学金1,奖学金2

Karan-1.Annual Fee->Economic Scholarship,Incapable Scholarship,2.Monthly Fee 

但是我得到的是

学生姓名-费用->奖学金1,学生姓名-费用->奖学金2

Karan-1.Annual Fee->Economic Scholarship,1.Annual Fee->Incapable Scholarship,2.Monthly Fee

这是怎么了?虽然我嵌套CONCAT,但没有得到预期的输出

CONCAT(student.en_ttl,'-',GROUP_CONCAT(DISTINCT fee.id,'.',fee.en_ttl,
    COALESCE(CONCAT('->',sch.en_ttl),''))) AS fee

SQL Fiddle

1 个答案:

答案 0 :(得分:1)

您基本上需要两级GROUP BY。因此,我们将需要在此处使用派生表。第一个子查询将在fee级别聚合;然后第二级将这些费用明细汇总到student级别。

此外,在较新(且与ANSI SQL兼容)的MySQL版本中,您需要确保SELECT子句中任何未聚合的列也应在GROUP BY子句中。

查询

SELECT
  CONCAT(stud_ttl,'-',GROUP_CONCAT(CONCAT(fee_det, COALESCE(CONCAT('->',fee_sch), '')))) AS fee
FROM 
(
  SELECT  student.ttl AS stud_ttl, 
        CONCAT(fee.id,'.',fee.ttl) AS fee_det,   
        Group_concat(DISTINCT sch.ttl) AS fee_sch 
  FROM   inv_id
       JOIN student
         ON student.id = inv_id.std
       JOIN inv_lst
         ON inv_lst.ftm = inv_id.ftm
       JOIN fee
         ON fee.id = inv_lst.fee
       JOIN sec_fee
         ON sec_fee.fee = fee.id
            AND sec_fee.cls = student.cls
            AND sec_fee.sec = student.sec
       LEFT JOIN std_sch
              ON std_sch.std = student.id
       LEFT JOIN sec_sch
              ON sec_sch.sch = std_sch.sch
                 AND sec_sch.fee = fee.id
       LEFT JOIN sch
              ON sch.id = sec_sch.sch
  GROUP  BY student.ttl, fee_det, fee.ttl
) dt
GROUP BY stud_ttl;

结果

| fee                                                                  |
| -------------------------------------------------------------------- |
| Karan-1.Annual->Economic Scholarship,Incapable Scholarship,2.Monthly |

View on DB Fiddle