如何使用LEFT JOIN进行计数?

时间:2012-03-20 15:50:11

标签: mysql sql

我需要与扫描大多数事情的公司制作一份清单......我有两张表,ExhibitorsLeads

Leads包含每个参展商所做的每一个“行动”。有时,在Exhibitors表中,同一家公司有两个帐户。例如,百事可乐可能有两个帐户。

链接两者的键/列称为ExhibitorID

我需要检索排名最靠前的前20名(leads中的COUNT(*)),但我需要按Exhibitors表中的公司进行分组。

我正在使用这个:

    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

但它没有按公司分组。谢谢你的帮助。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分:0)

您可以在公司上分组并加入ExhibitorID:

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