0

I would like to combine the following SQL queries to return a single table with the column names:

mnth, correct_predictions, incorrect_predictions

ts is a timestamp type.

SELECT monthname(ts) as mnth, count(*) AS correct_predictions
FROM prediction 
WHERE actual = 1 AND result = 1 OR actual = 0 AND result = 0
GROUP BY monthname(ts);

SELECT monthname(ts) as mnth, count(*) AS incorrect_predictions
FROM prediction 
WHERE actual = 0 AND result = 1 OR actual = 1 AND result = 0
GROUP BY monthname(ts);
0

2 Answers 2

3

Since MySQL treats booleans as 1 or 0 in a numeric context, you can just SUM the result of comparing actual and result to get your required columns:

SELECT MONTHNAME(ts) as mnth, 
       SUM(actual = result) AS correct_predictions,
       SUM(actual != result) AS incorrect_predictions
FROM prediction 
GROUP BY mnth;

Note that using MONTHNAME will result in values from every year being grouped together (e.g. May 2019 with May 2020). That may be what you want (or perhaps you are restricting the range of the query with a WHERE clause) but if not, you should use something like

EXTRACT(YEAR_MONTH FROM ts) AS mnth

to include the year in the value you are grouping by.

Sign up to request clarification or add additional context in comments.

3 Comments

@mrrain . . . This is actually much simpler. I would, however, advise you to include the year as well as the month name in the select and group by.
@GordonLinoff good point about the year, I've made a note about it in the answer.
@Nick very neat solution! :)
1

Try the following with case

SELECT 
    monthname(ts) as mnth,
    sum(case
            when (actual = 1 AND result = 1) OR (actual = 0 AND result = 0) then 1 else 0 
        end) 
   AS correct_predictions,
    sum(case
            when (actual = 0 AND result = 1) OR (actual = 1 AND result = 0) then 1 else 0 
        end) 
   AS incorrect_predictions
FROM prediction 
GROUP BY monthname(ts);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.