我尝试配置子查询,但在聚合/分组方面遇到了一些困难。子查询根据平均值选择计数。但是,将AVG(response) >= target
条件放在 WHERE 块中会导致"无效使用组功能"错误。将条件放在子查询的 HAVING 块中,除了它需要目标变量必须出现在 SELECT 块中COUNT,导致操作数应包含1列"错误。查询的副本如下。
我熟悉嵌套查询和聚合函数,但这种特殊组合拒绝合作。似乎应该有一个关键字"选择此字段进行比较/ HAVING但不要将其返回",或者我可能只是错误地制定了查询。不幸的是,这是由BIRT报告软件运行的,所以我不能(据我所知)抓取原始数据并手动聚合。
查询(为清晰起见略微修剪)如下:
SELECT
c.job_competency_id,
(
SELECT
COUNT(ar1.assessment_result_id)
FROM
recent_assessment AS ra1,
assessment_result AS ar1,
client_job_competency AS jc1
WHERE
ar1.assessment_id = a.assessment_id
AND ra1.assessment_id = ar1.assessment_id
AND ar1.job_competency_id = jc1.job_competency_id
AND ar1.job_competency_id = c.job_competency_id
AND AVG(ar1.response) >= jc1.target
GROUP BY jc1.job_competency_id
) AS n_meets
FROM
recent_assessment AS ra,
assessment AS a,
assessment_result AS ar,
client_job_competency AS jc,
job_competency AS c,
master_competency AS mc
WHERE
a.client_id = ?
AND ra.assessment_id = a.assessment_id
AND ar.assessment_id = a.assessment_id
AND c.job_competency_id = ar.job_competency_id
AND c.master_competency_id = mc.master_competency_id
AND jc.job_competency_id = c.job_competency_id;
如果重要,替代子查询就在这里:
(
SELECT
COUNT(ar1.assessment_result_id),
jc1.target
FROM
recent_assessment AS ra1,
assessment_result AS ar1,
client_job_competency AS jc1
WHERE
ar1.assessment_id = a.assessment_id
AND ra1.assessment_id = ar1.assessment_id
AND ar1.job_competency_id = jc1.job_competency_id
AND ar1.job_competency_id = c.job_competency_id
GROUP BY jc1.job_competency_id
HAVING AVG(ar1.response) >= jc1.target
) AS n_meets
如果你读到这里,谢谢你看看。如果有任何要求澄清,请告诉我。希望我在某个地方犯了一个愚蠢的错误。
答案 0 :(得分:0)
您不能在WHERE
子句中使用聚合函数,因为在选择所有行之前它不会处理聚合,这就是WHERE
子句确实
要解决HAVING
要求您选择要与之比较的列的问题,可以将其包装在另一级子查询中。然后外部查询可以返回您要放入SELECT
列表的一列。
(SELECT n_meets
FROM (
SELECT
COUNT(ar1.assessment_result_id) AS n_meets,
jc1.target
FROM
recent_assessment AS ra1,
assessment_result AS ar1,
client_job_competency AS jc1
WHERE
ar1.assessment_id = a.assessment_id
AND ra1.assessment_id = ar1.assessment_id
AND ar1.job_competency_id = jc1.job_competency_id
AND ar1.job_competency_id = c.job_competency_id
GROUP BY jc1.job_competency_id
HAVING AVG(ar1.response) >= jc1.target
) AS x) AS n_meets