MySQL IF/query conversion to PostgreSQL

I'm migrating a site from mysql to PostgreSQL (which I really like so far) but I have a question regarding a certain query. Please note that this was not a stored function- this was a string that was passed in manually in a python script(I am aware this is a terrible practice, but it's for an internal app only). In mysql, the query was structured like so:

SELECT 
  name,
  SUM(IF(is_correct, 1, 0)) AS correct,
  SUM(IF(is_correct, 0, 1)) AS wrong
FROM
  k_p AS p JOIN
  k_v AS v ON (variable_id=v.id)
WHERE
  content_type_id=%s %s %s
GROUP BY
  v.id
ORDER BY sort_order

is_correct is just a column with boolean data, either a 0 or 1. I realize you can't do straight IFs in postgres as you would in mysql. The documentation seems to suggest that the preferably conversion would be to use a case/when statement. I have experimented with no success. The SUM/IF statements are what are throwing me off- the rest of the query should be fine. Any advice would be greatly appreciated!

BONUS Question: How would you do it if one of the queries included:

 SUM(IF(ISNULL(is_correct), 0, 1)) AS wrong

Answers


You want to you the CASE construct:

SELECT 
  name,
  SUM(case when is_correct = 1 then 1 else 0 end) AS correct,
  SUM(case when is_correct = 1 then 0 else 1 end) AS wrong
FROM
  k_p AS p JOIN
  k_v AS v ON (variable_id=v.id)
WHERE
  content_type_id=%s %s %s
GROUP BY
  v.id
ORDER BY sort_order

select name, correct, wrong
from (
    SELECT 
      id,
      name,
      count(nullif(is_correct, false)) AS correct,
      count(nullif(is_correct, true)) AS wrong
    FROM
      k_p AS p JOIN
      k_v AS v ON (variable_id=v.id)
    WHERE
      content_type_id=%s %s %s
    GROUP BY
      v.id, name
)
ORDER BY sort_order

Need Your Help

Warning "Redefining module" when file is containing 2 Modules

elixir

Trying to figure out why below code is generating warning

What's the best way to save data locally in a WPF Application?

c# wpf save persistence

I'm building some WPF application to manage my time. I'd like to save time spans for work time on project for a calendar day.