简体   繁体   中英

MySQL joining two tables

I have two tables in MySQL. I would like to use bits from each table to come up with ONE table that has 3 columns. Month, Number of clients created and number of client contacted. NOTE: The number of contacted clients is of those that were created in that month. ALSO NOTE: that I am looking for just one point of contact with the client. The code below does not work

select month, count(tb_id), sum(contacted)
from (select ta.id, month(ta.created_at) as month,
             if(ta.client_id is null, 0, 1) as contacted
      from (select c.id, l.created_at, t1.client_id
            from client c left join
                 (select distinct client_id
                  from interactions
                  where created_at >= '2015-01-01'
                 ) t1
                on t1.client_id = c.id
           where c.created_at >= '2015-01-01'
          ) ta
     ) tb
group by month;   

Could this be what you want?

select 
    month(c.created_at) as month, 
    count(distinct c.id) as created, 
    sum(month(i.created_month) = month(c.created_at)) as contacted
from client c
left join (
    select distinct month(created_at) created_month, client_id 
    from interactions
) i on c.id = i.client_id 
   and month(c.created_at) = i.created_month
where c.created_at >= '2015-01-01' 
group by month(c.created_at);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM