如何在查询UNION ALL中设置列名?

时间:2016-08-10 14:55:54

标签: mysql union-all

我试图查询数据库以获取三列

{{1}}

但是将结果放在一列中:

enter image description here

如何向数据库发出请求。如果不可能,我可以确定查询的结果与我在请求中询问的顺序相同吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

在单列中,这是不可能的,每种类型需要三个单独的列

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 

答案 1 :(得分:0)

您真的希望根据sign result_enum列找到群组摘要:

SELECT SIGN(result_enum), SUM(result_enum) FROM result GROUP BY 1

这将产生:

+-------------------+------------------+
| SIGN(result_enum) | SUM(result_enum) |
+-------------------+------------------+
|                -1 |               -3 |  -- sign of -1 => "Negative"
|                 0 |                0 |  -- sign of  0 => "Neutral"
|                 1 |                9 |  -- sign of +1 => "Positive"
+-------------------+------------------+