如何对旋转 table 中的字段求和 ()

How to SUM() fields in a pivoted table

我有一个 MySQL table 有点像这样

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 |

我一直在阅读有关在 table 底部添加总行的内容,但它涉及 ROLLUP,它是 GROUP BY 的修饰符。正如您在上面看到的,我没有为此使用 GROUP BY,所以我不能使用 ROLLUP(或者我可以吗?)。

所以,我正在考虑在查询末尾添加这个

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

但我遇到了这个错误

Unknown column 'Income' in 'field list'

我有什么方法可以让它工作吗?

我认为这要么是因为您在第二个 select 中缺少一个 from,要么是因为您要从 table 本身尝试 select,它没有列收入和支出,因为除此之外,查询没问题..所以试试:

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)

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

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