Mysql 如何从历史记录表中统计每个状态的数字请参见输出

Mysql 如何从历史记录表中统计每个状态的数字请参见输出,mysql,sql,select,count,group-by,Mysql,Sql,Select,Count,Group By,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


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

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
我想计算perticular lead_id的个人状态编号

怎么做

但是对于LeaSyID 3710,必须考虑HyID 110,而在LeaSyID 3713

的情况下,不等于49意味着更大的HYID。 输出应如下所示:

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

因此,您需要从历史记录表中计算最近的状态。您可以通过连接到聚合,然后再次聚合来实现这一点。或者您可以使用
子字符串\u index()
/
组\u concat()
技巧:

ouput (for user_id 38)

status            No
converted   -     2   (lead_id is different)
pipeline       -  1
login      -      1
试试这个:

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;

你试过什么吗?