2014-12-05 65 views
1
lead table 

lead_id | name | mobile 
3710  aaa   888888 
3713  bbb   777777 
3714  ccc   666666 


如何計算的數字從歷史表中的每個狀態看輸出

user table 

user_id | email | pass | lead_id 
38   ppp   *****  3710 
39   qqq   *****  3713 
40   rrr   *****  3710 


History table 

h_id | lead_id | status | user_id 

49   3710   not dobale  38 
108   3713   doable  38 
109   3714   pipeline  38 
110   3710   converted  38 
111   3715   Login   38 
112   3713   converted  38 

我想算沒有indivisual地位perticuler lead_id。

如何做到這一點?

但lead_id 3710必須考慮h_id 110不是49意味着更大的h_id在lead_id的情況下,同樣的3713

輸出應該是這樣的:

ouput (for user_id 38) 

status   No 
converted -  2 (lead_id is different) 
pipeline  - 1 
login  -  1 
+2

你嘗試過什麼? – 2014-12-05 12:22:53

回答

1

所以你要算最近來自歷史記錄表的狀態。你可以通過加入到一個聚合中,然後再聚合。或者你也可以使用substring_index()/group_concat()招:

select last_status, count(*) 
from (select h.lead_id, substring_index(group_concat(status order by h_id desc), ',', 1) as last_status 
     from history 
     group by h.lead_id 
    ) h 
group by last_status; 
2

試試這個:

SELECT h.status, COUNT(DISTINCT lead_id) 
FROM History h 
INNER JOIN (SELECT user_id, lead_id, MAX(h_id) h_id 
      FROM History 
      GROUP BY user_id, lead_id 
     ) AS a ON h.user_id = a.user_id AND h.lead_id = a.lead_id AND h.h_id = a.h_id 
WHERE h.user_id = 38 
GROUP BY h.status 
相關問題