gpt4 book ai didi

mysql - CONCAT 内的 GROUP_CONCAT

转载 作者:行者123 更新时间:2023-11-29 09:57:55 26 4
gpt4 key购买 nike

数据库层次结构如下

  • 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。因此,我们需要在这里使用派生表。第一个子查询将在费用级别聚合;然后第二级将在学生级别汇总这些费用详细信息。

此外,在较新(且兼容 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

关于mysql - CONCAT 内的 GROUP_CONCAT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53522029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com