Search code examples
mysqlpostgresqlfunctionfiltercase-when

How create function filter PostgreSQL to MySQL?


How create function filter PostgreSQL to MySQL?

I tried as follows, but failed:

select
    CASE WHEN statusstorie = false and statusTwentyFive = true and category not in ('goals') and space = 'personal' THEN count(*) ELSE 0 END as "25%",
    CASE WHEN statusstorie = false and statusFifty = true and category not in ('goals') and space = 'personal' THEN count(*) ELSE 0 END as "50%",
    CASE WHEN statusstorie = false and statusSeventyFive = true and category not in ('goals') and space = 'personal' THEN count(*) ELSE 0 END as "75%",
    CASE WHEN statusstorie = false and statusOneHundred = true and category not in ('goals') and space = 'personal' THEN count(*) ELSE 0 END as "100%"
from goals 

PSQL Example:

select
    count(*) filter(where statusstorie = false and statusTwentyFive = true and category not in ('goals') and space = 'personal')  "25%",
    count(*) filter(where statusstorie = false and statusFifty = true and category not in ('goals') and space = 'personal') "50%",
    count(*) filter(where statusstorie = false and statusSeventyFive = true and category not in ('goals') and space = 'personal') "75%",
    count(*) filter(where statusstorie = false and statusOneHundred = true and category not in ('goals') and space = 'personal') "100%"
from goals 

Note: If possible I would like to replicate the function to MySQL

CREATE FUNCTION filter()


Solution

  • Does this work for you?

    select
        sum(CASE WHEN statusstorie = false and statusTwentyFive = true and category not in ('goals') and space = 'personal' THEN 1 ELSE 0 END) as "25%",
        sum(CASE WHEN statusstorie = false and statusFifty = true and category not in ('goals') and space = 'personal' THEN 1 ELSE 0 END) as "50%",
        sum(CASE WHEN statusstorie = false and statusSeventyFive = true and category not in ('goals') and space = 'personal' THEN 1 ELSE 0 END) as "75%",
        sum(CASE WHEN statusstorie = false and statusOneHundred = true and category not in ('goals') and space = 'personal' THEN 1 ELSE 0 END) as "100%"
    from goals