SQL - 将行中的前3个值相加为行的总和

时间:2017-07-25 22:04:34

标签: sql mariadb

我正在尝试对行进行求和 - 但行中只有前3个值......甚至可能吗?

Name - race1 - race2 - race3 - race4 - race5 - total
A    - NULL  - 10    -   9   -   5   -  4    - 25
B    - 10    - 3     - NULL  -   7   -  3    - 20
C    - 4     - NULL  - NULL  - NULL  -  2    - 6
...

甚至可能吗?我只知道如何汇总行中的所有值......

SELECT Name, 
(COALESCE(race1,0) + COALESCE(race2,0) + COALESCE(race3,0) + COALESCE(race4,0) + COALESCE(race5,0)) AS Total
FROM VIEW_race_results
WHERE 1;

感谢任何提示。使用10.1.19-MariaDB。 兹登卡

我在列中的表中有原始数据,所以我可以使用它....但我有参数的问题...但WHERE子句中的参数a.Model是未知的(我甚至尝试过WHERE EXIST试图在子查询中使用主查询中的参数....现在我迷路了......任何想法?

    SELECT a.Model, a. Name, a.Surname, a.AgeType, a.License, a.Klub,
(SELECT b.OrigPoints FROM VIEW_MiCR_result_data b WHERE b.Race='race1' AND a.Model=b.Model) AS race1,
(SELECT b.OrigPoints FROM VIEW_MiCR_result_data b WHERE b.Race='race2' AND a.Model=b.Model) AS race2,
(SELECT b.OrigPoints FROM VIEW_MiCR_result_data b WHERE b.Race='race3' AND a.Model=b.Model) AS race3,
(SELECT b.OrigPoints FROM VIEW_MiCR_result_data b WHERE b.Race='race4' AND a.Model=b.Model) AS race4,
(SELECT b.OrigPoints FROM VIEW_MiCR_result_data b WHERE b.Race='race5' AND a.Model=b.Model) AS race5,
(SELECT SUM(x.OrigPoints) FROM (SELECT OrigPoints FROM VIEW_MiCR_result_data WHERE Model=a.Model LIMIT 3) x ) AS Total
FROM VIEW_model a
WHERE 1;

1 个答案:

答案 0 :(得分:0)

在聚合之前取消隐藏然后使用变量:

select name, sum(race)
from (select name, race,
             (@rn := if(@n = name, @rn + 1,
                        if(@n := name, 1, 1)
                        )
             ) as rn
      from ((select name, race1 as race from t) union all
            (select name, race2 as race from t) union all
            (select name, race3 as race from t) union all
            (select name, race4 as race from t) union all
            (select name, race5 as race from t) 
           ) t cross join
           (select @n := '', @rn := 0) params
      where race is not null
      order by name, race desc
     ) nr
where rn <= 3
group by name;