简体   繁体   中英

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

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM