2012-03-20 80 views
1

我需要做一個列表與掃描的大多數事情,公司...我有兩個表,ExhibitorsLeads如何使用LEFT JOIN進行計數?

Leads包含每一個參展商做每個「動作」。有時,在Exhibitors表中,同一公司有兩個帳戶。例如,PepsiCO可能有兩個賬戶。

連接兩者的鍵/列被稱爲ExhibitorID

我需要檢索前導數最多的20個(所以COUNT(*)在leads),但我需要按公司Exhibitors表進行分組。

Curerntly我使用這個:

SELECT t2.ExhibitorID, t2.Company, t2.Username, t1.Count 
     FROM exhibitors AS t2 
     , (SELECT ExhibitorID, COUNT(*) AS Count 
       FROM leads AS l 
       WHERE l.ContractorID = 100 
       AND l.ShowID = "20120228AB" 
       GROUP BY l.ExhibitorID 
       ORDER BY COUNT(*) DESC 
       LIMIT 20) AS t1 
    WHERE t2.ExhibitorID = t1.ExhibitorID 
    ORDER BY t1.Count DESC 

但它沒有按公司。感謝你的幫助。

+2

首先,我會更改您的查詢以使用正確的ANSI JOIN語法。 INNER/LEFT/RIGHT JOIN – Taryn 2012-03-20 15:56:59

+0

此外,我不認爲你想要一個'LEFT JOIN',因爲你會得到零頭數(或參展商),這將不計算在內。我認爲你正在尋找'INNER JOIN' – swasheck 2012-03-20 16:05:34

+0

@swasheck除非公司有可能有0個相關的線索,並且他想要得到該公司返回的0個點數......在這種情況下,他會想要一個「左邊join'。 – 2012-03-20 16:07:35

回答

2
SELECT 
    e.Company, 
    COUNT(l.LeadId) AS Actions 
FROM 
    Exhibitors AS e 
    LEFT JOIN Leads AS l 
     ON l.ExhibitorID = e.ExhibitorID 
     AND l.ContractorID = 100 
     AND l.ShowID = "20120228AB" 
GROUP BY e.Company 
ORDER BY Actions DESC 
LIMIT 20; 
+0

不錯的查詢,但'LEFT JOIN'將返回NULL值來表示'Exhibitors'的不匹配值。 MySql會忽略集合函數的NULL值,但我認爲'INNER JOIN'在這裏更合適。 – swasheck 2012-03-20 16:07:37

+0

@swasheck如果參展商沒有匹配的線索怎麼辦?我認爲他希望在這種情況下計入0,而不是從結果集中省略參展商。 – 2012-03-20 16:09:05

+0

是的。往上看。 :) – swasheck 2012-03-20 16:09:31

3
select e.exhibitorid, count(l.leadid) 
    from leads l 
     inner join exhibitors on e.exhibitorid = l.exhibitorid 
     and l.showid = "20120228AB" and l.contractorid = 100 
    group by e.exhibitorid 
    order by count(l.contractorid) DESC 
    limit 20; 

如果有關係,這將仍然只是如果你想聯繫返回前20名,所以那時就似乎是一個MySQL的解決辦法在這裏MySQL's alternative to T-SQL's WITH TIES

0

你可以組公司,並加入參展商代碼:

select e.Company 
,  count(distinct l.LeadID) as LeadCount 
from Exhibitors e 
join Leads l 
on  l.ExhibitorID = e.ExhibitorID 
     and l.ShowID = "20120228AB" 
     and l.ContractorID = 100 
group by 
     e.Company 
order by 
     LeadCount DESC 
limit 20