0

我正在尝试计算一组数据有一个或多个失败的所有实例。

我也发现很难建立这个问题,所以我希望展示一个例子可以解释我想要实现的目标。

样本数据:

INSERT INTO test.answers (id, result_id, fail_all, fail_group) VALUES
    (1,1,0,1),  (2,1,0,1),  (3,1,0,1),  (4,1,0,0),
    (5,2,1,0),  (6,2,0,0),  (7,2,1,0),  (8,2,1,0),  (9,2,1,0),
    (10,3,0,1), (11,3,1,1), (12,3,0,1), (13,3,0,1), (14,3,0,1),
    (15,4,0,0), (16,4,0,0), (17,4,0,1), (18,4,0,1), (19,4,0,0), (20,4,0,1),
    (21,5,1,0), (22,5,0,1), (23,5,1,1), (24,5,0,1), (25,5,1,0), (26,5,0,1);

INSERT INTO test.results (id,team_id) VALUES
    (1,1), (2,1), (3,1), (4,2), (5,2);

然后我运行以下查询:

SELECT
    COUNT(IF(a.fail_all = 1,1,NULL)) AS count_fail_all,
    COUNT(IF(a.fail_group = 1,1,NULL)) AS count_fail_group,
    a.result_id
FROM test.answers AS a
GROUP BY a.result_id

结果:

count_fail_all, count_fail_group, result_id
0, 3, 1
4, 0, 2
1, 5, 3
0, 3, 4
3, 4, 5

我需要创建一个按 team_id 分组的查询,并计算每个结果有多少失败。如果一个结果有多个失败,那么这个整体结果就是失败。因此,如果上述查询中的结果计数为 3(例如:第一个结果),那么它应该只计为一个。fail_group 现在可以忽略,因为我相信 fail_all 的相同解决方案适用于 fail_group。

我希望的结果是:

team_id, amount_of_fails, amount_of_fails_per_group
1, 2, 2
2, 1, 2

我希望有人可以帮助我创建我需要的查询?我什至不知道如何开始。让我知道我是否可以做些什么来调整查询,因为我知道它不是很好问?

谢谢!

4

1 回答 1

1

If you want that output. Maybe something like this:

SELECT
  r.team_id,
  SUM(IF(a.fail_all = 1,1,0)) AS amount_fail_all,
  SUM(IF(a.fail_group = 1,1,0)) AS amount_fail_group
 FROM answers AS a
 JOIN results AS r on r.id=a.result_id
 GROUP BY r.team_id

This will get you this output:

team_id  amount_fail_all  amount_fail_group
1        2                2
2        1                2
于 2012-04-04T12:07:36.177 回答