选择union all - 为两个字段选择始终为零

时间:2014-01-29 13:26:27

标签: mysql union

我为我的朋友们写了一个足球桌程序,他们真的希望有更多的统计数据。但是我对于红队和黑队获胜和失败感到磕磕绊绊(W_S =赢黑; L_S =失去黑色)(W_R =赢红; L_R =失红)

这是我的架构并选择:

http://sqlfiddle.com/#!2/814a35/1/0

如您所见,W_S和L_S始终为零,W_R和L_R填充错误。

(schwarz = black; rot = red; tore = goals)

提前致谢!

修改

整个SELECT query

SELECT 
        `SpielerID` AS `id`, 
        `s`.`name` AS `name`, 
        COALESCE( (Sum(W_R) / NULLIF((Sum(W_R)+Sum(W_S))+(Sum(L_R)+Sum(L_S)), 0)), Sum(W_R) ) as 'rot_siegeRatio', 
        COALESCE( (Sum(W_S) / NULLIF((Sum(W_R)+Sum(W_S))+(Sum(L_R)+Sum(L_S)), 0)), Sum(W_S) ) as 'schwarz_siegeRatio', 
        Sum(W_R) as 'siegeCount', Sum(L_R) as 'niederlagenCount', (Sum(W_R)+Sum(L_R)) as 'spieleCount', 
        COALESCE( (Sum(W_R) / NULLIF((Sum(W_R))+(Sum(L_R)), 0)), Sum(W_R) ) as 'siegeRatio', Sum(Tore) as 'toreCount',
        Sum(Gegentore) as 'gegentoreCount',
        COALESCE( (Sum(Tore) / NULLIF(Sum(Gegentore), 0)), Sum(Tore) ) as 'toreRatio'
FROM 
        ( SELECT rot_spieler1 SpielerID, datetime,
          IF (rot_tore > schwarz_tore,1,0) W_R,
          IF (rot_tore < schwarz_tore,1,0) L_R,
          0 W_S,
          0 L_S,
          rot_tore Tore,
          schwarz_tore Gegentore
          FROM `kicker_spiele`
          WHERE datetime IS NOT NULL

          UNION ALL
          SELECT rot_spieler2 SpielerID, datetime,
          IF (rot_tore > schwarz_tore,1,0) W_R,
          IF (rot_tore < schwarz_tore,1,0) L_R,
          0 W_S,
          0 L_S,
          rot_tore Tore,
          schwarz_tore Gegentore
          FROM `kicker_spiele`
          WHERE datetime IS NOT NULL

          UNION ALL
          SELECT schwarz_spieler1 SpielerID, datetime,
          IF (schwarz_tore > rot_tore,1,0) W_S,
          IF (schwarz_tore < rot_tore,1,0) L_S,
          0 W_R,
          0 L_R,
          schwarz_tore Tore,
          rot_tore Gegentore
          FROM `kicker_spiele`
          WHERE datetime IS NOT NULL

          UNION ALL
          SELECT schwarz_spieler2 SpielerID, datetime,
          IF (schwarz_tore > rot_tore,1,0) W_S,
          IF (schwarz_tore < rot_tore,1,0) L_S,
          0 W_R,
          0 L_R,
          schwarz_tore Tore,
          rot_tore Gegentore
          FROM `kicker_spiele`
          WHERE datetime IS NOT NULL
         ) as ERG
LEFT JOIN `kicker_spieler` `s` ON ERG.SpielerID = s.id
GROUP by ERG.SpielerID

1 个答案:

答案 0 :(得分:0)

我希望这可以帮到你:

SELECT *,
(SELECT CASE 
    WHEN rot_tore > schwarz_tore 
    THEN 1 ELSE 0 
 END
) AS W_R,
(SELECT CASE 
    WHEN schwarz_tore > rot_tore
    THEN 1 ELSE 0 
 END
) AS L_R,
(SELECT CASE 
    WHEN schwarz_tore > rot_tore 
    THEN 1 ELSE 0 
 END
) AS W_S,
(SELECT CASE 
    WHEN rot_tore > schwarz_tore 
    THEN 1 ELSE 0 
 END
) AS L_S,
rot_tore Tore,
schwarz_tore Gegentore
FROM `kicker_spiele`
WHERE datetime IS NOT NULL