如何在不存在的条件下聚合并返回零



我有一个如下的表

case_no    history_no
A22010021   1
A22010021   2
A22010021   3
select
case 
when max(history_no) is null 
then 0 
else max(history_no) end as max
from
table
where
case_no = 'A22010022' 
group by
case_no

返回
max
Null

当我设置case_no = 'A22010021'时它返回

max
3

我想要的结果是得到1,其中不存在的case_no被提取。

max
0

这个问题的根本原因是什么?有什么方法可以做到这一点吗?

感谢

我认为group by子句在你的用例中是不需要的。

select coalesce(max(history_no),0)
from table_case_no where case_no='A220100234'

如果您想使用group by子句,请使用下面的查询来填充缺失的case no以放置0值。

select case_no,max(history_no) max_history_no
from table_case_no  where  case_no = 'A22010022' group by case_no
union
--below query for non-existent case no
select 'A22010022' as id,0 
where not exists
(
select 1 from table_case_no where case_no='A22010022'
)
;