2015-11-19 247 views
0

我知道這類話題有很多問題,但我找不到任何有助於解決問題的問題。如何將這兩個查詢合併到一個查詢中?

我有兩個工作查詢。我想將它們組合成一個查詢。當我嘗試合併它們時,顯示的數據不正確。但是,當他們分開時,數據是正確的。

查詢1:

Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor', 
concat('$', sum(a.amount)) as 'Total Paid' 
From Donor d, Pledge p, Payment a 
Where d.DonorId=p.DonorId 
and p.pledgeId = a.pledgeId 
group by d.donorid; 

輸出:

+--------------+------------+ 
| Donor  | Total Paid | 
+--------------+------------+ 
| John Smith | $3500.00 | 
| Linda Smith | $250.00 | 
| Jack Clinton | $200.00 | 
| Jane Doe  | $2100.00 | 
+--------------+------------+ 

問題2:

Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor', 
concat('$', sum(a.amount)) as 'Pocket' 
From Donor d, Pledge p, Payment a 
Where (a.CompanyId is null) 
and d.DonorId=p.DonorId 
and p.pledgeId = a.pledgeId 
group by d.donorid; 

輸出:

+--------------+----------+ 
| Donor  | Pocket | 
+--------------+----------+ 
| John Smith | $1750.00 | 
| Linda Smith | $100.00 | 
| Jack Clinton | $200.00 | 
| Jane Doe  | $2100.00 | 
+--------------+----------+ 

當組合:

Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor', 
concat('$', sum(a.amount)) as 'Total Paid', 
concat('$', sum(a2.amount)) as 'Pocket' 
From Donor d, Donor d2, Pledge p, Pledge p2, Payment a, Payment a2 
where d.donorId=p.donorId 
and p.pledgeId = a.pledgeId 
and (a2.CompanyId is null) 
and d2.DonorId = p2.DonorId 
and p2.pledgeId = a2.PledgeId 
group by d.DonorId; 

輸出:

這些查詢的
+--------------+------------+-----------+ 
| Donor  | Total Paid | Pocket | 
+--------------+------------+-----------+ 
| John Smith | $24500.00 | $20750.00 | 
| Linda Smith | $1750.00 | $12450.00 | 
| Jack Clinton | $1400.00 | $8300.00 | 
| Jane Doe  | $14700.00 | $8300.00 | 
+--------------+------------+-----------+ 

每個人都有捐助者的名字列,並與一些貨幣值的列。在我的最後一個查詢中,我想要一個包含捐助者名稱的列,一個標記爲「全額付款」的列和一個標記爲「口袋」的列。當我將這兩個查詢結合起來時,「總收入」列和「口袋」列全部搞砸了。

我知道這可能很難幫助沒有表架構,但我想我會給它一個鏡頭。提前致謝。

回答

0

試試這個:

select 
    'Donor',concat('$',sum('Total Paid')) as 'Total Paid',concat('$',sum('Pocket')) as 'Pocket' 
from(
     Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor', 
     sum(a.amount) as 'Total Paid', 0 as Pocket 
     From Donor d, Pledge p, Payment a 
     Where d.DonorId=p.DonorId 
     and p.pledgeId = a.pledgeId 
     group by d.donorid 

     union all 

     Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor', 
     0 as 'Total Paid',sum(a.amount) as 'Pocket' 
     From Donor d, Pledge p, Payment a 
     Where (a.CompanyId is null) 
     and d.DonorId=p.DonorId 
     and p.pledgeId = a.pledgeId 
     group by d.donorid 
    ) group by Donor; 

注:如果您使用的是MySQL數據庫,你應該使用單引號的列名backticks( 「`」)來代替。

+0

感謝您的建議。這幾乎可行。當我自己嘗試第一個子查詢並且當我嘗試第二個子查詢時,我會得到正確的輸出。但是,當我嘗試整件事時,所有內容都顯示爲0.列標題是正確的,但所有值都是0.我不知道爲什麼它會這樣做。有關這個問題的任何建議? – ethanm1