我有一个像这样的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'有什么办法能让这件事成功吗?
发布于 2016-02-15 15:12:24
如果添加一个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 ROLLUPhttps://stackoverflow.com/questions/35412628
复制相似问题