MySQL - Sum Table 2显示所有表1描述的列值

时间:2017-05-22 13:44:28

标签: mysql

我分别为交易和类别提供了以下表格。 我正在尝试编写一个查询,它将在下面的查询表中显示结果。

我试过以下

SELECT IFNULL(categories.Name,'Total') AS category,
       IFNULL(SUM( transactions.Amount),0) AS amount,
       categories.Color 
FROM transactions,categories 
WHERE categories.CatID = transactions.CatID 
GROUP BY  categories.Name WITH ROLLUP

然而,这并没有给我B类。我希望我的B类显示为0 - 0,如下所示。请帮忙..

交易

+-----------+------------+------------+--------+
| TransID   |  SaleDate  | CatID      | Amount |
+-----------+------------+------------+--------+
|         1 | 2012-02-10 | 1          |     10 |
|         2 | 2012-02-10 | 3          |     10 |
|         3 | 2012-02-10 | 3          |     20 |
|         4 | 2012-02-10 | 1          |     25 |
|         5 | 2012-02-10 | 1          |     35 |
|         6 | 2012-02-10 | 3          |      5 |
|         7 | 2012-02-10 | 3          |      5 |
+-----------+------------+------------+--------+

分类

+------------+------+----------+
| CatID      | Name | Color    | 
+------------+------+----------+
|          1 |   A  |    Green |
|          2 |   B  |    Red   |
|          3 |   C  |    Blue  |
+------------+------+----------+

获得结果

+-----------+----------------+------------+
| Category  |  Amount        | Color      |
+-----------+----------------+------------+
|         A | 70             | Green      |
|         B | 40             | Blue       |
|     Total | 110            | Blue       |
+-----------+----------------+------------+

要求的结果

+-----------+----------------+------------+
| Category  |  Amount        | Color      |
+-----------+----------------+------------+
|         A | 70             | Green      |
|         B | 0              | Red        |
|         C | 40             | Blue       |
|     Total | 110            | Pink       |
+-----------+----------------+------------+

1 个答案:

答案 0 :(得分:1)

您正在寻找left join rollup

select coalesce(c.category, 'total') as category,
       coalesce(sum(t.amount), 0) as amount,
       coalesce(c.color, 'pink') as color -- this is weird
from categories c left join
     transactions t
     on c.catid = t.catid
group by c.category with rollup;