Search code examples
mysqlmysql-error-1064

How can I find the percentage of my users whose birth date is between 1980 and 1996.


i'm trying to find the percentage of my users whose birth date is between 1980 and 1996.

I can't find how to do it:

SELECT Sum
(WHEN userBirthDate BETWEEN '1980/01/01' AND '1996/12/31'
THEN 1 ELSE 0 END) * 100 / Count(userID) as total
FROM user

The error mysql returns is syntax:

 ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN userBirthDate BETWEEN '1980/01/01' AND '1996/12/31' THEN 1 ELSE 0)' at line 1

how can i do it?

Thank you in advance


Solution

  • SELECT Sum(case WHEN userBirthDate BETWEEN '1980/01/01' AND '1996/12/31'
                    THEN 1 
                    ELSE 0 
           END) * 100 / Count(userID) as total
    FROM `user`
    

    or just

    SELECT Sum(userBirthDate BETWEEN '1980/01/01' AND '1996/12/31') * 100 / Count(userID) as total
    FROM `user`