简体   繁体   English

MySql-连接三个表并按一个表中的一列分组

[英]MySql - Three tables joined and grouped by one column from one table

I have four tables all in all, 我总共有四张桌子,

tbluser, tblstudentlead, tblcalls, tbldocusin tbluser,tblstudentlead,tblcalls,tbldocusin

I want to group the results of my queries by tbluser.id 我想按tbluser.id对查询结果进行分组

here is my query: 这是我的查询:

select t.fk, MAX(u.firstname) as Name, t.Leads, t.Calls, t.Docu
from
(


SELECT salesuserId as fk, COUNT(id) Leads
FROM tblstudentlead 
WHERE createdon
BETWEEN  '2015-01-01'
AND  '2016-01-01'
GROUP BY salesuserId


union all
SELECT createdBy as fk, COUNT(id) Calls
FROM tblcalls
WHERE createdon
BETWEEN  '2015-01-01'
AND  '2016-01-01'
GROUP BY createdBy


union all
SELECT createdBy as fk, COUNT(id) Docu
FROM tbldocusin
WHERE createdon
BETWEEN  '2015-01-01'
AND  '2016-01-01'
AND status = 'completed'
GROUP BY createdBy
) t

inner join tbluser u on (t .fk=u.id)
group by u.id
order by u.id asc

But it only gives me this result 但这只会给我这个结果

fk | Name | Leads 

The result I need is: 我需要的结果是:

fk | Name | Leads | Docu

Thanks hope you help me 谢谢你希望我帮忙

You will probably be better off using subqueries if I understand your question correctly. 如果我正确理解了您的问题,使用子查询可能会更好。 Here's an example: 这是一个例子:

select u.id, 
       u.firstname as Name, 
       (select count(id) Leads
        from tblstudentlead t
        where t.salesuserId = u.id and createdon between '2015-01-01' and '2016-01-01') as Leads,
       (select count(id) Calls
        from tblcalls c
        where c.createdBy = u.id and createdon between '2015-01-01' and '2016-01-01') as Calls,
       (select count(id) Docu
        from tbldocusin d
        where d.createdBy = u.id createdon between '2015-01-01' and '2016-01-01') as Docu
from tbluser u 
order by u.id

Alternatively you could use the subquery in a join : 另外,您可以使用子查询中join

select u.id, 
       u.firstname as Name, 
       l.Leads,
       c.Calls,
       d.Docu
from tbluser u join
    (select salesuserId as id, count(id) Leads
    from tblstudentlead 
    where createdon between '2015-01-01' and '2016-01-01'
    group by salesuserId) l on u.id = l.id join 
    (select createdBy as id, count(id) Calls
    from tblcalls 
    where createdon between '2015-01-01' and '2016-01-01'
    group by createdBy) c on u.id = c.id join 
    (select createdBy as id, count(id) Calls
    from tbldocusin 
    where createdon between '2015-01-01' and '2016-01-01'
    group by createdBy) d on u.id = d.id 
order by u.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM