2013-07-31 61 views
2

我對SQL/MySQL和Stackoverflow非常陌生,我嘗試通過iReport創建查詢(儘管我不必使用iReport)for SugarCRM CE。我需要的是創建一個報告,顯示鏈接到特定「用戶」(員工)的「推介」,「語音郵件」,「電子郵件」和「電話號碼」的數量。我現在的查詢已經建立了作品;但是它會多次運行數據,生成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 

我將不勝感激任何指導!

回答

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; 
+0

你FAST)和(CASE WHEN leadtype_c = '推薦' THEN 1 ELSE 0 END)我想在我的答案添加 – realnumber3012

+0

謝謝!這正是我需要的 – spearman008

0

您可以使用COUNTCASE此:

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 

,以符合您確切的結果,你應該使用一個OUTER JOIN代替,但是這給你的想法。

+0

謝謝你的幫助! – spearman008

+0

@ user2636343 - np,很高興我們可以幫忙! – sgeddes