我對事務和類別分別具有以下表格。 我想寫一個查詢,將給我下面的查詢表中顯示的結果。MySQL - 總和表2列值顯示所有表1描述
我曾嘗試以下
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總如下。請幫助..
交易
+-----------+------------+------------+--------+
| 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 |
+-----------+----------------+------------+
[本文](https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/)使用維恩使用ANSI 92標準而不是上面使用的ANSI 89標準來有效解釋連接類型。在你的情況下,需要一個外連接來保留不在兩個數據集中的記錄。 – xQbert