如何对我的列 "horse" 中的所有值执行此 "MySQL" 查询...此处此查询在我的列 "horse" 中执行 1 个值

how to execute this "MySQL" query for all values that are in my column "horse" ... here this query execture 1 value in my column "horse"

如何对所有执行“MySQL”查询 我专栏中的值 ?

这是我的 table

Table A
|----------------------|---------------------|------------------|
|          id          |        CL           |     horse        |    
|----------------------|---------------------|------------------|
|           1          |        1er          |     C.Ferland    |
|           2          |        5e           |     Abrivard     |
|           3          |        3e           |     P. Hawas     |
|----------------------|---------------------|------------------|

我希望输出为:

+------------+--------+---------+---------+-----------+
|    horse   | Top_1  | Top_2_3 | TOP_4_5 | TOP_total |
+------------+--------+---------+---------+-----------+
| C. Ferland | 0.1757 |  0.2788 |  0.1892 |    0.6436 |
|  Abrivard  | 0.0394 |  0.1231 |  0.1575 |    0.3199 |
| P. Hawas   | 0.0461 |  0.1263 |  0.1092 |    0.2816 |
+------------+--------+---------+---------+-----------+

目前,我正在运行查询我的马列中的值。 这非常有效。

SELECT horse,
sum(case when `cl` = '1er' then 1 else 0 end)/count(*) as Top_1, 
sum(case when `cl` BETWEEN 2 AND 3 then 1 else 0 end)/count(*) as Top_2_3,
sum(case when `cl` BETWEEN 4 AND 5 then 1 else 0 end)/count(*) as TOP_4_5,
sum(case when `cl` BETWEEN 1 AND 5 then 1 else 0 end)/count(*) as TOP_total
FROM p_mu.cachedate
WHERE horse ="C.Ferland";

如何针对我的“马”列中的所有值调整此查询。 谢谢你的帮助..

您可以使用条件聚合,但您想要的结果显示您想要计算 整个数据集 的平均值,而不仅仅是组的行。 Window 函数派上用场:

select
    horse,
    sum(cl = 1)      / count(*) over() top_1,
    sum(cl in (2,3)) / count(*) over() top_2_3,
    sum(cl in (4,5)) / count(*) over() top_4_5,
    sum(cl <= 5)     / count(*) over() top_1_5
from p_mu.cachedate
group by horse

如果你想过滤给定的马,你需要一个派生的 table:

select *
from (
    select
        horse,
        sum(cl = 1)      / count(*) over() top_1,
        sum(cl in (2,3)) / count(*) over() top_2_3,
        sum(cl in (4,5)) / count(*) over() top_4_5,
        sum(cl <= 5)     / count(*) over() top_1_5
    from p_mu.cachedate
    group by horse
) t
where horse = 'C.Ferland'

这仅适用于 MySQL 8.0。在早期版本中,您可以改用子查询:

select
    horse,
    sum(cl = 1)      / x.cnt top_1,
    sum(cl in (2,3)) / x.cnt top_2_3,
    sum(cl in (4,5)) / x.cnt top_4_5,
    sum(cl <= 5)     / x.cnt top_1_5
from p_mu.cachedate
inner join (select count(*) cnt from p_mu.cachedate) x
group by horse