SQL选择列,然后从下一列数

时间:2019-02-02 20:22:13

标签: count mariadb

我给转诊表格结构中,场裁判是唯一的:

ID  pid  ref   ref_by  
1    1   k      NAN
2    2   l      k
3    3   m      k
4    4   n      l

用户表为:

id    name   
1     john  
2     Bob  
3     Tim   
4     Rob   

我需要在下一列中获取id,pid,ref和ref的计数。基于引用的数量,将分别为它们分配一些常数100的点,结果应如下所示。

pid  name   ref   number_of_referals  points_earned 
1     john   k      2                   200
2     Bob    l      1                   100
3     Tim    m      0                     0
4     Rob    n      0                     0

1 个答案:

答案 0 :(得分:0)

您需要2个加入:
users表到referrals的第一个,对分组和计数引荐的查询的第二个:

select 
  r.id, u.name, r.ref,
  case when c.counter is null then 0 else c.counter end number_of_referals,
  case when c.counter is null then 0 else c.counter end * 100 points_earned
from users u inner join referrals r
on r.pid = u.id
left join (select ref_by, count(*) counter from referrals group by ref_by) c
on c.ref_by = r.ref
order by r.id

请参见demo