如何用 sql 中的分组进行计数

How to count with a group by in sql

我的查询如下所示:

select 
    no, sub_no, date, id, count(distinct sub_no) as count
from 
    (select no, sub_no, date, id 
     from pre_test where type = 'B' and date = '2020-10-02'
     group by no, sub_no, date, id 
     having min(test_activity) = max(test_activity) 
        and min(test_activity) = 'APPROVED'
        and min(test_type) = max(test_type) 
        and min(test_type) = 'COMPLETED') as x 
group by 
    no, sub_no, date, id

我希望从这个查询中看到每个 no 中有多少 sub_no 具有 type = B,并且所有 sub_no 已被批准并完成。

我实际得到的是:

no   sub_no    date          id        count
--------------------------------------------
01    01-01    2020-10-02     a         1
01    01-02    2020-10-02     a         1

虽然我预计查询会 return:

no   date          id   count
-----------------------------
01  2020-10-02     a      2

并且还会显示所有具有 0 值的 no

我应该如何解决我的查询?

谢谢。

group by clause

中删除 sub_no
select no, date, id, count(distinct sub_no) as count
from (select no, sub_no, date, id 
      from pre_test where type = 'B' and date = '2020-10-02'
      group by no, sub_no, date, id 
      having min(test_activity) = max(test_activity ) and min(test_activity ) = 'APPROVED'
      and min(test_type) = max(test_type) and min(test_type) = 'COMPLETED') as x group by no, date, id