2017-07-25 60 views
0

我想總結行 - 但只有行中的前3個值...是可能的嗎?SQL - 將行中的前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。 Zdenka

我在列中的表中有原始數據,所以我可以使用它....但我有問題的參數...但參數a.Model在WHERE子句是未知的(我甚至嘗試過在哪裏存在當我試圖在子查詢中使用參數從主查詢....現在我失去了...任何想法

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; 
+0

做你有更多的專欄或只顯示比賽的5個? –

+0

你的數據結構d似乎不太好,比賽應該在記錄中,而不是在列中。 – Shadow

+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; 
+0

恐怕這對我來說太複雜了...我收到了錯誤消息#1267 - 非法混合排序規則(utf8_general_ci,IMPLICIT)和(utf8_czech_ci,IMPLICIT)進行操作'= ' – Zdenka

+0

@Zdenka。 。 。如果您有非法的排序組合,那麼數據庫/服務器的默認值與存儲在字段中的數據不同。您可以使用「COLLATE」關鍵字來對齊排序規則。 –