Nikita Ribakovs
Nikita Ribakovs

Reputation: 315

IF / CASE statement in SQL

I'm really struggling to find an answer to this issue. I want to write an if or case statement that changes a value in another column. If column 'check' is 0 then column 'points' should be 0 as well.

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

Upvotes: 1

Views: 100

Answers (2)

Blue
Blue

Reputation: 22911

You can't "SET" columns in a case statement, you can return the value. Think of the case statement as a variable column. Return '0' AS Saleable (Or whatever column you wish to name).

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

Upvotes: 3

Bing
Bing

Reputation: 746

You can select to count only lines matching your left join like so:

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 

Upvotes: 0

Related Questions