GROUP_CONCAT 在 CONCAT 中

GROUP_CONCAT within CONCAT

数据库层次结构如下

  • Student Name
    • List of fee Assigned to Each Student
      • List of Scholarship Assigned to Each Fee

作为结构,预期输出为

学生姓名-费用->奖学金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

你基本上需要两级GROUP BY。所以,我们需要在这里使用 Derived Table。第一个子查询将在 fee 级别聚合;然后第二级将在 student.

级别汇总这些费用详细信息

此外,在 MySQL 的较新(和 ANSI SQL 兼容)版本中,您需要确保 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