2017-06-15 215 views
1

我真的很努力地找到這個問題的答案。我想寫一個if或case語句來改變另一列的值。如果「檢查」列是0,那麼列'點'也應該爲0。SQL中的IF/CASE語句

SELECT club_name, COALESCE(club_winner,0) AS 'check', COUNT(*) AS points, 
    CASE 
    WHEN check = '0' 
    THEN points = '0' 
    ELSE check 
    END as Saleable 
    FROM clubs c 
    LEFT JOIN club_results cr ON c.club_id = cr.club_winner 
    GROUP BY club_name ORDER BY points DESC 
+1

你的意思是「當檢查=‘0’,則‘0’ELSE END點爲點」? –

+0

是否要在表格中更新它,或者直接顯示它? –

+0

這是MySQL還是Transact-SQL? – Black

回答

3

您不能在case語句中「SET」列,您可以返回值。將case語句看作可變列。返回'0'AS Saleable(或任何您想要命名的列)。

SELECT club_name, COALESCE(club_winner,0) AS 'check', COUNT(*) AS points, 
CASE 
WHEN COALESCE(club_winner,0) = 0 
THEN 0 
ELSE COUNT(*) 
END AS points_or_0_if_check_is_0 
FROM clubs c 
LEFT JOIN club_results cr ON c.club_id = cr.club_winner 
GROUP BY club_name ORDER BY points_or_0_if_check_is_0 DESC 
+1

您以後在select子句中不能重複使用較早的列別名。 – Donnie

+0

哎呀,@Donnie。思想檢查是一個常規專欄(錯過了上面的) – FrankerZ

+0

也是'points'別名。 – Donnie

0

可以選擇只計算符合左連接,像這樣的行:

SELECT 
    club_name, 
    COUNT(
     CASE WHEN 
      club_winner IS NOT NULL 
     THEN 
      CR.id 
     ELSE 
      NULL 
     END 
    ) AS `points` 
FROM 
    clubs C 
LEFT JOIN 
    club_results CR ON C.club_id = CR.club_winner 
GROUP BY 
    C.club_id 
ORDER BY 
    points DESC