首页 > 解决方案 > 获取未读消息的计数

问题描述

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

我想获得 3 列requestType,CategoryGroupreadStatus列数

结果将requestType一直显示categoryGroup,如果readStatus是假的,那么它将显示它的计数,如果所有readStatus都是真的,requestType那么返回 0。

同样,如果requestTypeisNULL和 Blank 相同categoryGroup(来自表 A,subcategoryId 12 和 13 来自categoryGroup表 B 中的相同),则 categoryGroup 应显示为 BLANK 并应保存 ( readStatus=0) NULL 和 BLANK的计数

结果计数

我写的查询只返回列和计数,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;

上述查询的预期结果是:

在此处输入图像描述

标签: mysqlsql

解决方案


我会做类似的事情:

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

推荐阅读