简体   繁体   English

CONCAT中的GROUP_CONCAT

[英]GROUP_CONCAT within CONCAT

Database hierarchical structure is as follow 数据库的层次结构如下

  • Student Name 学生姓名
    • List of fee Assigned to Each Student 分配给每个学生的费用清单
      • List of Scholarship Assigned to Each Fee 分配给每项费用的奖学金列表

As structure, expected output is 作为结构,预期输出为

Student Name-Fee->Scholarship1, Scholarship2 学生姓名-费用->奖学金1,奖学金2

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

But what I am getting 但是我得到的是

Student Name-Fee->Scholarship1, Student Name-Fee->Scholarship2 学生姓名-费用->奖学金1,学生姓名-费用->奖学金2

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

What is wrong in here ? 这里有什么问题? Though I am nesting CONCAT , but not getting expected output 虽然我嵌套了CONCAT ,但是没有得到预期的输出

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

SQL Fiddle SQL小提琴

You basically need to two levels of GROUP BY . 您基本上需要两个级别的GROUP BY So, we will need to use a Derived Table here. 因此,我们将需要在此处使用派生表。 First subquery will aggregate at the level of fee ; 第一个子查询将在fee级别汇总; and then the second level would aggregate those fee details at the level of student . 然后第二级将在student级别汇总这些费用详细信息。

Also, in newer (and ANSI SQL compliant) versions of MySQL, you need to ensure that any non-aggregated column in the SELECT clause should be in the GROUP BY clause as well. 另外,在较新的(和ANSI SQL兼容)版本的MySQL中,您需要确保SELECT子句中任何未聚合的列也应在GROUP BY子句中。

Query 询问

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;

Result 结果

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

View on DB Fiddle 在数据库小提琴上查看

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

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