我正在尝试根据表格中的列创建一个列表并对值进行求和。我有下表
id | box1 | box2 | box3
------------------------
111 | 1 | 0 | 1
111 | 0 | 1 | 1
111 | 1 | 1 | 1
111 | 0 | 0 | 1
我需要结果像这样
column | sum
------------
box1 | 2
box2 | 2
box3 | 4
我尝试使用union all并选择每个列,但我能够获得正确的列标题。我能够得到总和,但我无法弄清楚如何获得列名。
SELECT SUM(box1) as box1Count FROMqueue
UNION ALL
SELECT SUM(box2) as box2Count FROM queue
UNION ALL
SELECT SUM(box3) as box3Count FROM queue
答案 0 :(得分:0)
您可以对SELECT
子句中的列值进行硬编码:
SELECT 'box1' AS col, SUM(box1) as box1Count FROM queue
UNION ALL
SELECT 'box2', SUM(box2) as box2Count FROM queue
UNION ALL
SELECT 'box3', SUM(box3) as box3Count FROM queue