2015-01-21 80 views
1

我有什麼:Mysql的嵌套查詢,1桌,3個查詢,個人成績

2表

- table_benefactor (id and benefactor names) 
- table_realstate (house adress, rent, paidrent flag) 

If paidrent = 0 (unpaid) 
If paidrent = 1 (paid) 

我需要什麼:

1嵌套查詢,返回我像下面的結果

name | totalrent | paid | unpaid 
_________________________________ 
Jhon | 1,000.00 |100.00| 900.00 
Doe | 2,500.00 |500.00| 2,000.00 
Chris| 800.00 |0.00 | 800.00 

我曾嘗試:

我嘗試過很多方法,但他們非給我的結果,我所需要的,他們得到接近,但不是我所需要的,這是我的查詢 - >

如果我這樣做這樣它會正是我想要的,但不能退貨的方式,我需要它

(SELECT table_realstate.benefactor, name, SUM(rent) totalrent 
FROM table_realstate, table_benefactor 
WHERE flag = 0 
AND table_realstate.benefactor = table_benefactor.id 
GROUP BY benefactor 
ORDER BY name ASC) 
UNION ALL 
(SELECT table_realstate.benefactor, name, SUM(rent) unpaid 
FROM table_realstate, table_benefactor 
WHERE flag = 0 
AND table_realstate.benefactor = table_benefactor.id 
AND table_realstate.paidrent = 0 
GROUP BY benefactor 
ORDER BY name ASC) 
UNION ALL 
(SELECT table_realstate.benefactor, name, SUM(rent) paid 
FROM table_realstate, table_benefactor 
WHERE flag = 0 AND table_realstate.benefactor = table_benefactor.id 
AND table_realstate.paidrent = 1 
GROUP BY benefactor 
ORDER BY name ASC) 

結果:

name | totalrent 
_________________ 
Jhon | 1,000.00 
Doe | 2,500.00 
Chris| 800.00  
Jhon | 100.00 
Doe | 500.00 
Jhon | 900.00 
Doe | 2,000.00 
Chris| 800.00 

所以我有一直在努力這樣的事情:

如果我不喜歡這樣的結果的結構是什麼,我需要,但數學和恩人的名字出來的錯誤 - >

SELECT table_benefactor.name, SUM(rent) totalrent, SUM(rent) unpaid, SUM(rent) paid 
    FROM table_realstate, table_benefactor, 
    (SELECT table_realstate.benefactor, name, SUM(rent) totalrent 
    FROM table_realstate, table_benefactor 
    WHERE flag = 0 
    AND table_realstate.benefactor = table_benefactor.id 
    UNION ALL 
    SELECT table_realstate.benefactor, name, SUM(rent) unpaid 
    FROM table_realstate, table_benefactor 
    WHERE flag = 0 
    AND table_realstate.benefactor = table_benefactor.id 
    AND table_realstate.paidrent = 0 
    UNION ALL 
    SELECT table_realstate.benefactor, name, SUM(rent) paid 
    FROM table_realstate, table_benefactor 
    WHERE flag = 0 AND table_realstate.benefactor = table_benefactor.id 
    AND table_realstate.paidrent = 1) abc 
GROUP BY table_realstate.benefactor 

結果:

name | totalrent | paid | unpaid 
_________________________________ 
Jhon | 119.200 |119.200 | 119.200 
Jhon | 1,800.02 |1,800.02 | 1,800.02 
Jhon | 29,1964.2 |29,1964.2| 29,1964.2 
Jhon | 27,000.00 |27,000.00| 27,000.00 

你可以看到恩人的名字重複自己,值都遍佈在這個地方。

我試過其他的東西,但不想讓帖子比已經存在的時間長。

回答

0

我想你只是想條件聚合。如果paidrent標誌只取值0和1,如代碼所示,則這特別簡單:

select b.name, sum(re.rent) as total_rent, 
     sum(re.rent * re.paidrent) as paid, 
     sum(re.rent * (1 - re.paidrent)) as paid, 
from table_benefactor b join 
    table_realestate re 
    on b.id = re.benefactor 
group by b.id, b.name;