2015-08-28 61 views
2

我有2個表,我需要加入並根據需求總結數量。這是表格結構。加入2個表X和Y來顯示總和()結果事件表Y是空的

Customer 
--------------------------------------------------- 
ID | Name  | Tel   | Sex 
--------------------------------------------------- 
1 | John  | 123 XXXX  | M 
2 | Peter  | 456 XXXX  | M 
3 | Alice  | 789 XXXX  | F 
4 | Amy   | 147 XXXX  | F 

Transaction 
--------------------------------------------------- 
ID | CustID | TranID | Books | Pens | Rulers 
--------------------------------------------------- 
1 | 1 | Jan | 1 | 1 | 0 
2 | 1 | Feb | 1 | 0 | 0 
3 | 2 | Jan | 1 | 0 | 1 
4 | 2 | Jan | 1 | 0 | 0 
5 | 3 | Feb | 0 | 1 | 1 
6 | 4 | Feb | 1 | 1 | 0 
7 | 3 | Feb | 1 | 1 | 0 
8 | 4 | Feb | 0 | 0 | 1 
9 | 3 | Jan | 1 | 0 | 0 
10 | 2 | Jan | 1 | 1 | 0 

Required Results (Sex=F, TranID=Jan, Sum:Books, Pens & Rulers) 
-------------------------------------------------------------- 
Name  | Tel   | Sex | B.TOT | P.TOT | R.TOT 
-------------------------------------------------------------- 
Alice  | 789 XXXX | F | 1 | 0 | 0 
Amy   | 147 XXXX | F | 0 | 0 | 0 

我試着用下面的SQL語句,只要事務表不是空的,它就會工作。

select 
`customer`.name, 
`customer`.tel, 
`customer`.sex, 
sum(if(`transaction`.TranID = 'JAN',books,0)) as B.Tot, 
sum(if(`transaction`.TranID = 'JAN',pens,0)) as P.Tot, 
sum(if(`transaction`.TranID = 'JAN',rulers,0)) as R.tot, 
from 
`customer` 
left join 
`transaction` 
on 
`customer`.id = `transaction`.custid 
where 
`customer`.sex = 'F' 
Group by 
`customer`.id, 
order by 
`customer`.name ASC 

如何修改上述內容以顯示客戶列表,其中SEX ='F'即使事務表完全爲空?

+0

愚蠢的我...只是發現,我無意中更新SEX字段設置爲NULL在另一個單獨的進程。它正在工作。 –

+0

但是因爲我已經發布了這個問題,我可以問一下我用if()和sum()的方法是正確的嗎?由於'transaction'.TranID也是必需的條件。有沒有更好的方法來重寫這個sql語句? –

+0

看起來不錯,如果.TranID不爲空 – Drew

回答

0

SQL查詢

我希望這個查詢能夠解決您的問題:

SELECT 
    c.name, 
    c.tel, 
    c.sex, 
    IFNULL(SUM(t.books), 0) 'B.TOT', 
    IFNULL(SUM(t.pens), 0) 'P.TOT', 
    IFNULL(SUM(t.rulers), 0) 'R.TOT' 
FROM 
    customer c 
     LEFT JOIN 
    `transaction` t ON t.custid = c.id AND t.TranID = 'Jan' 
WHERE 
    c.sex = 'F' 
GROUP BY c.id 
ORDER BY c.name;