2017-05-22 120 views
0

我對事務和類別分別具有以下表格。 我想寫一個查詢,將給我下面的查詢表中顯示的結果。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  | 
+-----------+----------------+------------+ 
+0

[本文](https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/)使用維恩使用ANSI 92標準而不是上面使用的ANSI 89標準來有效解釋連接類型。在你的情況下,需要一個外連接來保留不在兩個數據集中的記錄。 – xQbert

回答

1

你正在尋找一個left joinrollup

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; 
+0

謝謝戈登。你是男人! - 如果我可能會問如何編寫查詢以在我的交易表中列SaleDate的日期範圍內顯示交易。 –

+1

@IshmaelChibvuri。 。 。你可以在'on'子句的'transactions'上添加條件。 –

相關問題