PHP/Mysql -> 每个用户 billing/paydate 的平均值

PHP/Mysql -> AVG of billing/paydate per User

我有两个 table: t_address -> 使用用户地址 t_billing -> 包含 t_address 用户的账单信息

它们由 t_billing.bil_addressref = t_address.adr_ref

链接

在账单中table,我有一个字段 bil_date -> 账单日期 issued/sent bil_paydate -> 账单支付日期

我不想确定"worst Payers",意思是需要平均最长支付时间的人。

例如:

没有。 -- bil_date -- bil_paydate -- adr_ref
1 -- 2017-01-01 -- 2017-01-10 - 1
2 -- 2017-02-01 -- 2017-02-10 - 1
3 -- 2017-03-01 -- 2017-03-05 - 1
4 -- 2017-04-01 -- 2017-04-05 - 1
5 -- 2017-01-01 -- 2017-01-30 - 2
6 -- 2017-03-01 -- 2017-03-30 - 2
...

所以
对于 ADR 2,平均支付时间为 29 天
对于 ADR 1,平均支付时间为 6.5 天

我想要获得最差付款人的前 5 个结果,从最差到不太差排序。

我尝试了几个查询和想法,但没有遇到正确的想法:/

有什么建议吗?谢谢,斯蒂芬。

您可以使用 join 、 group by 和 limit

  select adr_ref,  sum( datediff(bil_paydate,bil_date ))/ count(*) my_result
  from t_address
  inner join  t_billing on t_billing.bil_addressref = t_address.adr_ref

  group by adr_ref
  order by  my_result desc 
  limit 5