我的数据库有这个要求,如下所示
我想获取3列requestType
,CategoryGroup
和readStatus
列的计数
结果将显示所有requestType
和categoryGroup
,如果readStatus
为false,则显示其计数,如果在同一readStatus
中所有requestType
为true,则返回0。
同样,如果requestType
是NULL
并且在同一categoryGroup
中为空白(来自表A,子类别ID 12和13来自表B中的相同categoryGroup
),则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;
上述查询的预期结果是:
最佳答案
我会做类似的事情:
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