如何在透视表中的SUM()字段

时间:2016-02-15 15:03:10

标签: mysql pivot

我有一个像这样的MySQL表

Table 'club_funds'
| Income    | Label                   | Amount  |
+-----------+-------------------------+---------+
| 1         | Membership fees         |    1000 |
| 0         | Gathering party costs   |     500 |
| 1         | Garage sale profit      |     250 |

我设法变成了这个

| Label                   | Income | Expense |
+-------------------------+--------+---------+
| Membership fees         |   1000 |         |
| Gathering party costs   |        |     500 |
| Garage sale profit      |    250 |         |

使用此查询

SELECT Label,
IF (income = 1, amount, null) AS `Income`,
IF (income = 0, amount, null) AS `Expense`
FROM club_funds

现在,我想在底行添加一个总计。

| Label                   | Income | Expense |
+-------------------------+--------+---------+
| Membership fees         |   1000 |         |
| Gathering party costs   |        |     500 |
| Garage sale profit      |    250 |         |
| Total                   |   1250 |     500 |

我一直在阅读有关在表格底部添加总行的信息,但它涉及ROLLUP,它是GROUP BY的修饰符。如上所示,我没有使用GROUP BY因此我无法使用ROLLUP(或者我可以吗?)。

所以,我想在查询结尾添加这个

UNION SELECT 'Total', SUM(Income), SUM(Expense)

但是我收到了这个错误

Unknown column 'Income' in 'field list'

我能以任何方式完成这项工作吗?

2 个答案:

答案 0 :(得分:3)

我认为这可能是因为你在第二个选择中缺少一个来自或者因为你要从表中选择它自己,它还没有列收入和费用,因为其他的,查询很好..所以试试:

SELECT Label,
IF (income = 1, amount, null) AS `Income`,
IF (income = 0, amount, null) AS `Expense`
FROM club_funds
UNION
(SELECT 'Total' as `label`,
       sum(case when income = 1 then amount else 0) as `Income`,
       sum(case when income = 0 then amount else 0) as `Expense`
FROM club_funds)

答案 1 :(得分:2)

如果添加ROLLUP子句,则可以使用GROUP BY

SELECT COALESCE(Label, 'Total') AS Label,
       SUM(IF (income = 1, amount, null)) AS `Income`,
       SUM(IF (income = 0, amount, null)) AS `Expense`
FROM club_funds
GROUP BY Label WITH ROLLUP

在MySQL中,你也可以简化你的查询:

SELECT COALESCE(Label, 'Total'),
       SUM((income = 1)*amount) AS `Income`,
       SUM((income = 0)*amount) AS `Expense`
FROM club_funds
GROUP BY Label WITH ROLLUP

Demo here