我有一些子查询的查询。
表示子查询在那里工作正常,但是当在一个大查询中放在一起时,返回的结果就会重复。查询:
SELECT
kpi.kra_id AS kra,
kpi.id AS kpi,
(
SELECT
ROUND(AVG(sp.progress), 2)
FROM `submissions` AS sub
LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
WHERE sub.programme = 'programme'
AND sub.submission_year = '2015/2016'
AND sub.state = '2'
AND sub.period = '1'
AND pm.kpi_id = kpi.id
) AS p1_programme_score,
(
SELECT
ROUND(AVG(sp.progress), 2)
FROM `submissions` AS sub
LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
WHERE sub.programme = 'programme'
AND sub.submission_year = '2015/2016'
AND sub.state = '2'
AND sub.period = '2'
AND pm.kpi_id = kpi.id
) AS p2_programme_score
FROM `kpis` kpi
LEFT JOIN `performance_measures` pm ON kpi.id = pm.kpi_id
GROUP BY kpi.id
结果如下:
我正在寻找的是每个KPI,以显示每个p1和p2列的自己的分数。
答案 0 :(得分:1)
我不知道如何解决问题,因为您没有包含数据结构。但是,我可以找出可能的原因。
每个子查询都有这样的条件:
AND pm.kpi_id = kpi.id
子查询中都没有pm
和kpi
,因此这只会重复外部查询中的join
条件。据推测,您希望kpi_id
匹配子查询中的某些表,sub
或sp
。
答案 1 :(得分:0)
确实非常感谢Jerodev和xQBert让我指向正确的方向。新的工作查询如下:
SELECT
kpi.kra_id AS kra,
kpi.id AS kpi,
(
SELECT
ROUND(AVG(sp.progress), 2)
FROM `submissions` AS sub
LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
LEFT JOIN `performance_measures` pm ON pm.id = sp.pm_id
WHERE sub.programme = 'programme'
AND sub.submission_year = '2015/2016'
AND sub.state = '2'
AND sub.period = '1'
AND pm.kpi_id = kpi.id
) AS p1_programme_score,
(
SELECT
ROUND(AVG(sp.progress), 2)
FROM `submissions` AS sub
LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
LEFT JOIN `performance_measures` pm ON pm.id = sp.pm_id
WHERE sub.programme = 'programme'
AND sub.submission_year = '2015/2016'
AND sub.state = '2'
AND sub.period = '2'
AND pm.kpi_id = kpi.id
) AS p2_programme_score
FROM `kpis` kpi
GROUP BY kpi.id
此查询的不同之处在于performance_measures表的连接位置。它是在主要查询上,但它需要绑定到子查询,所以我移动它和VIOLA!