获取未读邮件的数量

时间:2019-09-19 13:07:36

标签: mysql sql

我对我们的数据库有此要求,如下所示

我想获得3列requestTypeCategoryGroup和计数readStatus

结果将显示所有requestTypecategoryGroup,如果readStatus为假,则显示计数,如果所有readStatus为true相同的requestType然后返回0。

如果requestTypeNULL并且空白在同一categoryGroup中(从表A,子类别ID 12和13来自表B中的同一categoryGroup),则categoryGroup应该显示为BLANK,并应同时包含(readStatus=0)NULL和BLANK的计数

Result count

我编写的查询仅返回有关readStatus=false的列和计数,并显示其总数。

select coalesce( m.requestType, "") as requestType,
  count(m.messageId) as count, 
  s.categoryGroup categoryGroup 
from mb_message m 
join mb_subcategory s on m.subCategoryId = s.subCategoryId 
where m.readStatus=0 
and m.storeId = ? 
and countryCode= ?
and m.modifiedDate >= ?
group by m.requestType, m.subCategoryId;

上述查询的预期结果是:

enter image description here

1 个答案:

答案 0 :(得分:0)

我会做类似的事情:

select
  requesttype, 
  sum(cnt) as cnt,
  categorygroup
from (
  select
    case when a.requesttype is null or a.requesttype = '' 
         then 'BLANK' else a.requesttype end as requesttype,
    case when a.readstatus = 0 then 1 else 0 end as cnt,
    b.categorygroup
  from tablea a
  join tableb b on b.subcategoryid = a.subcategoryid
) x
group by requesttype, categorygroup