2

就此而言,我对 SQL/MySQL 和 Stackoverflow 非常陌生,我正在尝试通过iReport(尽管我不必使用iReport)为SugarCRM CE创建一个查询。我需要创建一个报告,显示链接到特定“用户”(员工)的“推荐”、“语音邮件”、“电子邮件”和“Call_ins”的数量。我目前设置的查询有效;但是,它多次运行数据,生成超过 200 页的报告。这是我目前正在使用的代码:

SELECT
 ( SELECT COUNT(*) FROM `leads` INNER JOIN `leads_cstm` ON `leads`.`id` = `leads_cstm`.`id_c` WHERE (leadtype_c = 'Referral' AND users.`id` = leads.`assigned_user_id`) ),
 ( SELECT COUNT(*) FROM `leads` INNER JOIN `leads_cstm` ON `leads`.`id` = `leads_cstm`.`id_c` WHERE (leadtype_c = 'VM' AND users.`id` = leads.`assigned_user_id`) ),
 ( SELECT COUNT(*) FROM `leads` INNER JOIN `leads_cstm` ON `leads`.`id` = `leads_cstm`.`id_c` WHERE (leadtype_c = 'Email' AND users.`id` = leads.`assigned_user_id`) ),
 users.`first_name`,users.`last_name`
FROM
 `users` users,
 `leads` leads

我将不胜感激任何指导!

4

2 回答 2

2

您想使用条件求和。以下使用 MySQL 语法:

SELECT sum(leadtype_c = 'Referral') as Referrals,
       sum(leadtype_c = 'VM') as VMs,
       sum(leadtype_c = 'Email') as Emails,
       users.`first_name`, users.`last_name`
FROM users join
    `leads`
     on  users.`id` = leads.`assigned_user_id` INNER JOIN
     `leads_cstm`
     ON `leads`.`id` = `leads_cstm`.`id_c`
group by users.id;
于 2013-07-31T02:21:37.497 回答
0

您可以为此使用COUNTwith :CASE

SELECT u.first_name, 
    u.last_name, 
    count(case when leadtype_c = 'Referral' then 1 end),
    count(case when leadtype_c = 'VM' then 1 end),
    count(case when leadtype_c = 'Email' then 1 end)
FROM users u
    JOIN leads l ON u.id = l.assigned_user_id
    JOIN leads_cstm lc ON l.id = lc.id_c
GROUP BY u.id

为了匹配您的确切结果,您可能应该改用 an OUTER JOIN,但这给了您这个想法。

于 2013-07-31T02:23:03.320 回答