SQL 计算有多少行具有相同的值并根据条件求和

SQL count how many rows have the same value and do the sum on condition

今天我有一个问题要问你。我有这个 table

oddId risk resultCode finalResult
1 6.66667 2 1
2 7.14286 2 1
3 8.33333 2 1
4 8.33333 2 2
5 10 2 1
6 10 2 2
7 10 2 2
8 10 2 2
9 11.1111 1 2
10 11.1111 2 2
11 12.5 2 1
12 12.5 2 2
13 12.5 1 1
14 12.5 2 1
15 12.5 2 1
16 12.5 1 2
17 12.5 1 1
18 12.5 1 2
19 12.5 2 1
20 14.2857 2 2
21 14.2857 1 2
22 14.2857 2 2
23 16.6667 2 2
24 16.6667 1 2
25 16.6667 1 1

这份工作我需要

  1. 按“风险”对行进行分组
  2. 计算有多少行具有相同的“风险”值
  3. 计算“resultCode”和“finalResult”中有多少行具有相同的值

SELECT  `risk`, `resultCode`, `finalResult`, 
        ( SELECT  CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END
            FROM  matches
            WHERE  `resultCode` = t.`finalResult`
              AND  `oddId` = t.`oddId`
        ) equal
    FROM  matches t
    WHERE  `finalResult` IS NOT NULL
    ORDER BY  `t`.`risk` ASC

我可以得到“相等”的列。

risk resultCode finalResult equal
6.66667 2 1 0
7.14286 2 1 0
8.33333 2 1 0
8.33333 2 2 1
10 2 1 0
10 2 2 1
10 2 2 1
10 2 2 1
11.1111 1 2 0
11.1111 2 2 1
12.5 2 1 0
12.5 2 2 1
12.5 1 1 1
12.5 2 1 0
12.5 2 1 0
12.5 1 2 0
12.5 1 1 1
12.5 1 2 0
12.5 2 1 0
14.2857 2 2 1
14.2857 1 2 0
14.2857 2 2 1
16.6667 2 2 1
16.6667 1 2 0
16.6667 1 1 1

SELECT  `risk`, COUNT(`risk`) as total
    FROM  `matches`
    WHERE  `finalResult` IS NOT NULL
    GROUP BY  `risk`
    ORDER BY  `risk` DESC

我可以获得“总计”列。


现在我还想要一个列,在其中按“风险”分组并将“相等”列相加(合并为“更正”),以便...

risk corrects total
6.66667 0 1
7.14286 0 1
8.33333 1 2
10 3 4
11.1111 1 2
12.5 3 9
14.2857 2 3
16.6667 2 3

但是我不知道该怎么做...有人可以帮我吗? 非常感谢

MySQL - MyISAM - 5.6.48-88.0

你第一个sql太乱了,没看清楚答案

SELECT
    `risk`,
    COUNT( `risk` ) AS total,
    sum(case when resultCode = finalResult then 1 else 0 end) corrects
FROM
    `matches` 
WHERE
    `finalResult` IS NOT NULL 
GROUP BY
    `risk` 
ORDER BY
    `risk` DESC