2010-11-24 35 views
0

我的SQL-fu對此太虛弱了,我甚至不確定在一次SQL調用中是否可能。是否可以在單個SQL查詢中的三個表中選擇多個條件計數?

鑑於我有以下表格:

PARTNER 
+----+--------+ 
| id | name | 
+----+--------+ 
| 1 | bloggs | 
| 2 | jones | 

PARTNER MANAGER 
+----+--------------+------+ 
| id | partner_id | name | 
+----+--------------+------+ 
| 1 | 1   | fred | 
| 2 | 2   | dave | 

COMPANY 
+----+--------------------+--------+----------+ 
| id | partner_manager_id | name | active | 
+----+--------------------+--------+----------+ 
| 1 | 1     | comp1 | true  | 
| 2 | 1     | comp2 | false | 
| 3 | 2     | comp3 | true  | 
| 4 | 2     | comp4 | true  | 
| 5 | 2     | comp5 | true  | 
| 6 | 2     | comp6 | true  | 

我想輸出在一個SQL調用如下:

+--------------+--------------------+----------------------+ 
| partner_name | n_active_companies | n_inactive_companies | 
+--------------+--------------------+----------------------+ 
| bloggs  | 1     | 1     | 
| jones  | 4     | 0     | 

我可以使用連接三個表,有兩個LEFT JOINs但如何我可以彙總計數(有或沒有WHERE條款)正在逃避我。

我吠叫了錯誤的樹,可以這麼說嗎?

+0

我喜歡,如果你從一個單一的statment – Sudantha 2010-11-24 12:54:20

回答

2

這讓你最那裏的方式:

SELECT 
    partner_manager_id, 
    SUM(CASE WHEN active THEN 1 ELSE 0 END) AS n_active_companies, 
    SUM(CASE WHEN active THEN 0 ELSE 1 END) AS n_inactive_companies 
FROM COMPANY 
GROUP BY partner_manager_id 

你的問題的其餘部分基本上是問如何這個結果加入到其餘的表。正如你所指出的,要做到這一點,請使用JOIN。

SELECT 
    PARTNER.name, 
    T1.n_active_companies, 
    T1.n_inactive_companies 
FROM 
PARTNER 
LEFT JOIN PARTNER_MANAGER ON partner_id = PARTNER.id 
LEFT JOIN 
(
    SELECT 
     partner_manager_id, 
     SUM(CASE WHEN active THEN 1 ELSE 0 END) AS n_active_companies, 
     SUM(CASE WHEN active THEN 0 ELSE 1 END) AS n_inactive_companies 
    FROM COMPANY 
    GROUP BY partner_manager_id 
) T1 
ON T1.partner_manager_id = PARTNER_MANAGER.id 
+0

這是我在寫答案的核心要使用一個SQL視圖...只是需要加入到翻譯partner_manager_id合作伙伴。名字 – chezy525 2010-11-24 13:01:45

0
select p.name "Partner Name" 
, c1.cnt "n_active_companies" 
, c2.cnt "n_inactive_companies" 
from partner p 
, (select partner_manager_id id, count(partner_manager_id) cnt from company where active = 'true' group by partner_manager_id) c1 
, (select partner_manager_id id, count(partner_manager_id) cnt from company where active = 'false' group by partner_manager_id) c2 
where c1.id = p.id 
and c2.id = p.id 
0
select p.name as 'partner_name', 
     sum(case when active then 1 else 0) as 'n_active_companies', 
     sum(case when active then 0 else 1) as 'n_inactive_companies' 
from COMPANY c 
    join PARTNER_MANAGER pm on c.partner_manager_id = pm.id 
    join PARTNER p on pm.partner_id = p.id 
group by p.name 
相關問題