通过不处理多个计数进行分组

时间:2014-12-14 23:16:03

标签: mysql sql

我有以下SQL:

SELECT team_instance.id,COUNT(dropkicks.id) * 3
FROM team_instance
INNER JOIN player_instance ON team_instance.id = player_instance.team_instance_id
INNER JOIN dropkicks ON player_instance.id = dropkicks.kicker_id
WHERE dropkicks.success = true
GROUP BY team_instance.id

按预期工作 - 它返回按team_instance id分组的计数值。

我需要做的是组合多个计数,以便team_instance显示两个表的总数(惩罚和dropkicks):

SELECT id AS team_instance_id,
(
SELECT COUNT(dropkicks.id) * 3
FROM team_instance
INNER JOIN player_instance ON team_instance.id = player_instance.team_instance_id
INNER JOIN dropkicks ON player_instance.id = dropkicks.kicker_id
WHERE dropkicks.success = true


) + 

(
SELECT COUNT(penalty_kicks.id) * 3
FROM team_instance
INNER JOIN player_instance ON team_instance.id = player_instance.team_instance_id
INNER JOIN penalty_kicks ON player_instance.id = penalty_kicks.kicker_id
WHERE penalty_kicks.success = true
)
AS total
 FROM team_instance
 GROUP BY team_instance.id

但这确实无法正常工作,因为team_instances的值是相同的(并且它们不应该是)。

2 个答案:

答案 0 :(得分:2)

您需要将子查询与外部查询相关联。此外,假设group by是一个id,您不需要id。在子查询中加入team_instance也是多余的,所以我认为这更符合您的要求:

SELECT id AS team_instance_id,
       (SELECT COUNT(dropkicks.id) * 3
        FROM player_instance INNER JOIN
              dropkicks
              ON player_instance.id = dropkicks.kicker_id
        WHERE team_instance.id = player_instance.team_instance_id AND dropkicks.success = true
       ) + 
       (SELECT COUNT(penalty_kicks.id) * 3
        FROM player_instance INNER JOIN
             penalty_kicks
             ON player_instance.id = penalty_kicks.kicker_id
        WHERE team_instance.id = player_instance.team_instance_id AND penalty_kicks.success = true
       ) AS total
FROM team_instance;

您的值相同的原因是因为您的子查询聚合了所有表中的所有值 - 不计算特定团队的事物。

答案 1 :(得分:0)

你需要把它放在一个选择

SELECT team_instance.id, COUNT(dropkicks.id) * 3 + COUNT(penalty_kicks.id) * 3 as total
FROM team_instance
INNER JOIN player_instance ON team_instance.id = player_instance.team_instance_id
Left JOIN dropkicks ON player_instance.id = dropkicks.kicker_id and dropkicks.success = true
Left JOIN penalty_kicks ON player_instance.id = penalty_kicks.kicker_id and penalty_kicks.success = true
GROUP BY team_instance.id