按几个字段分组时对行进行计数

时间:2019-07-09 14:39:25

标签: mysql sql

我有关注查询

Select parent.*,

( Select ?????????
     from  event e
     where  e.company_id = parent.company_id
       AND e.event_type_id in (10, 11, 12)
       AND  
        e.email in 
         (Select DISTINCT u.email
             from  users u  where  u.parent_id = parent.id )


     and e.subject_id in 
        (Select DISTINCT s.subject_id from  subjects s  where s.parent_id = parent.id ) 
    GROUP by e.email, e.subject_id ) as done

from parent_table parent

我需要放点东西????????计算子查询的行数

我试图用另一个子查询将其包装

Select count(*)  from (.........)

但是在这种情况下,我的内部查询看不到父表

Unknown column 'parent.company_id' in 'where clause'

子查询本身返回表,如

----------------------------------------
|   email   |    subject    |    count  |
----------------------------------------
|   email1  |    1          |    1      |
|   email2  |    5          |    3      |
|   email3  |    20         |    22     |

因此,其事件按电子邮件主题对计数

在顶层,我只需要一些这样的对

UPDT:

似乎

COUNT(DISTINCT e.email, e.subject_id) 代替 GROUP by e.email, e.subject_id ) 对我来说很好

1 个答案:

答案 0 :(得分:0)


( Select COUNT(DISTINCT e.email, e.subject_id)
     from  event e
     where  e.company_id = parent.company_id
       AND e.event_type_id in (10, 11, 12)
       AND  
        e.email in 
         (Select DISTINCT u.email
             from  users u  where  u.parent_id = parent.id )


     and e.subject_id in 
        (Select DISTINCT s.subject_id from  subjects s  where s.parent_id = parent.id )  ) as done

from parent_table parent