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
我想不计算相关的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
答案 0 :(得分: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
答案 1 :(得分: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;