简体   繁体   中英

How can I combine two SQL queries returning multiple columns into separate columns of the same table?

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);

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 (eg 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.

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);

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