Roman Roman - 3 months ago 10
MySQL Question

How to set the column name in the query UNION ALL?

I'm trying to query the database to get the three columns

(SELECT SUM(result_enum) AS Positive FROM result WHERE result_enum > 0)
UNION ALL
(SELECT SUM(result_enum) AS Negative FROM result WHERE result_enum < 0)
UNION ALL
(SELECT SUM(result_enum) AS Neutral FROM result WHERE result_enum = 0)


but get the result in one column:

enter image description here

How to make a request to the database. If It not possible, Can I be sure that the result of the query will be in the same order in which I asked him in the request?

Thanks!

Answer

In single column this is not possible,you need three separate columns for each type

SELECT  SUM(CASE WHEN result_enum > 0 THEN result_enum ELSE 0 END) AS Positive,
        SUM(CASE WHEN result_enum < 0 THEN result_enum ELSE 0 END) AS Negative, 
        0 AS Neutral 
FROM TableName