循环列并分配0/1 MySQL

时间:2017-01-12 14:59:36

标签: mysql sql loops select case-when

我有一个关于参加活动的消费者的MySQL数据库。该数据库包含所有已连接的用户表,事件表和签入表。但是数据库仅包含有关用户进入某个事件的信息。 我想要一个循环遍历几个事件的查询,并检查用户是否转到其中一个事件,并给出结果:

Preffered result

我尝试过以下查询:

select attend.idperson, attend.idmeeting,
    (select case when 
    attend.idmeeting = 2901 or
    attend.idmeeting = 9044 or
    attend.idmeeting = 9161 or
    attend.idmeeting = 2626
    then 1 else 0 end) as attended
from attend
join meetings on attend.idmeeting = meetings.idmeeting
join persons on attend.idperson = persons.id
where meetings.verified = 1;

但是这会带来所有人实际去过的会议,并且在查询出席的情况下在选择案例中分配1个会议,其余为0。目标是使用逻辑回归预测出勤率,此解决方案会使所有进一步的用户数据产生偏差。

1 个答案:

答案 0 :(得分:0)

您可以建立所有人和会议的列表,然后加入出席详情:

select distinct a1.*, 
       case
         when attend.idperson is null then 0 
         else 1 
       end as attended
from 
(
 select meetings.idmeeting, persons.id as p_id
 from meetings
 cross join persons
 where meetings.verified = 1
) a1
left join attend
  on attend.idmeeting = a1.idmeetings
  and attend.personid a1.p_id