问题
我有一个工作存储过程 (SP),它接受 3 个参数(一个 id、一个起始日期和一个截止日期)。这个 SP 在我的测试系统中运行良好,其中从t1.name
中返回的所有值GROUP_CONACT
都很短,并且GROUP_CONCAT
.
问题是当我把它放到 LIVE 系统中时,还有一些问题需要添加,GORUP_CONCAT
而且t1.name
值比预期的要长得多。
从我在尝试调试脚本时可以看到的结果来看,问题似乎是该变量@SQL
无法存储从GROUP_CONACT
查询中返回的所有信息。
编码
CREATE DEFINER=`root`@`localhost` PROCEDURE `team_analyst_results`(in var1 int, in var2 DATE, in var3 DATE)
BEGIN
SELECT
GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(question_id = \'',
question_id,
'\', Pass, Null)) AS ',
CONCAT('\'', t1.name, '\'')))
INTO @SQL FROM
smhubdb.questions t1
INNER JOIN
smhubdb.check_questions t2 ON t1.id = t2.question_id
INNER JOIN
smhubdb.quality_checks t3 ON t2.check_id = t3.id
INNER JOIN
smhubdb.users t4 ON t3.check_person = t4.id
WHERE
t4.team_id = var1
AND
t3.checked_date BETWEEN var2 AND var3
GROUP BY t3.check_person;
SET @SQL = CONCAT('SELECT t1.id AS "'"Check ID"'", t4.name AS "'"Name"'" ,DATE_FORMAT(t1.checked_date, "'"%d-%m-%Y"'") AS "'" Check Date "'" , ', @SQL, ' , t1.notes AS "'"Notes"'", CONCAT(ROUND((SUM(CASE WHEN t2.pass = 1 THEN t3.value ELSE 0 END) / SUM(t3.value) * 100),0),"'""'") AS "'"Score"'" FROM smhubdb.quality_checks t1 LEFT JOIN smhubdb.check_questions t2 ON t1.id = t2.check_id LEFT JOIN smhubdb.questions t3 on t2.question_id = t3.id INNER JOIN smhubdb.users t4 ON t1.check_person = t4.id WHERE t4.team_id = ''', var1 ,''' AND t1.checked_date BETWEEN ''', var2 ,''' AND ''', var3 ,''' GROUP BY t1.id ORDER BY t1.id DESC');
PREPARE stmt FROM @SQL;
EXECUTE stmt;
END
我试过的
我尝试设置@SQL
为局部变量(显然这删除了@),但随后我在尝试准备代码底部的语句时遇到错误,解释它不需要局部变量。
代码的目的
该代码用于从未知数量的结果中填充数据透视表。这意味着我需要第一GROUP_CONCAT
部分在 end 语句上构建列名以进行准备。
预期产出
问题的数量不会知道,问题的名称也不会知道。
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
<table>
<thead>
<th>
Name
</th>
<th>
Check ID
</th>
<th>
Date
</th>
<th>
Question1
</th>
<th>
Question2
</th>
<th>
Question3
</th>
<th>
Question4
</th>
<th>
Notes
</th>
<th>
Score
</th>
</thead>
<tbody>
<tr>
<td>
Joe Bloggs
</td>
<td>
1
</td>
<td>
08/11/2018
</td>
<td>
Pass
</td>
<td>
Pass
</td>
<td>
Null
</td>
<td>
Pass
</td>
<td>
Some Notes
</td>
<td>
75%
</td>
<tr>
</tbody>
</table>