oracle - max with case

时间:2011-03-07 14:52:37

标签: sql oracle

select case when cntrctr_lcns_seq_no is null
                                   then 1
                                   else max(cntrctr_lcns_seq_no)
                                   end as cntrctr_lcns_seq_no
                                   from nuwmsweb.cntrctr_lcns_info
                                    where third_party_id = thirdPartyId
                                    group by third_party_id

我想你看看我想做什么。获取特定ID的max seq_no。但我得到的错误是“不是一个单独的群组条款”。

此select语句是较大插入的一部分。

谢谢!

更新:这是整个声明

insert into nuwmsweb.CNTRCTR_LCNS_INFO
    (third_party_id,cntrctr_lcns_seq_no,cntrctr_lcns_no,
    lcns_st_cd,certfn_level_type_cd,cntrctr_type_cd,cut_tap_authy_ind,
    stat_type_nm)
    VALUES(thirdPartyId,(select max(case when cntrctr_lcns_seq_no is null
                                   then 1
                                   else cntrctr_lcns_seq_no
                                   end) as cntrctr_lcns_seq_no
                                   from nuwmsweb.cntrctr_lcns_info
                                    where third_party_id = thirdPartyId
                                    group by third_party_id
                                    ),
          licenseNumber,licenseState,licenseLevel,licenseType,cutTap,status);

4 个答案:

答案 0 :(得分:1)

最大聚合函数将忽略空值,因此您不需要case语句或group by,因为您希望在整个返回集合上使用max。

select
    coalesce(max(cntrctr_lcns_seq_no), 1) as cntrctr_lcns_seq_no
from nuwmsweb.cntrctr_lcns_info
where third_party_id = thirdPartyId

答案 1 :(得分:1)

我想你想要:

select coalesce (max(cntrctr_lcns_seq_no),1) as cntrctr_lcns_seq_no
  from nuwmsweb.cntrctr_lcns_info
 where third_party_id = thirdPartyId

(或者,如果您愿意,可以使用Oracle的nvl代替ANSI的coalesce

答案 2 :(得分:0)

试试这个:

select  max(case when cntrctr_lcns_seq_no is null then 1
        else cntrctr_lcns_seq_no end) as cntrctr_lcns_seq_no
from nuwmsweb.cntrctr_lcns_info
where third_party_id = thirdPartyId                                     
group by third_party_id 

答案 3 :(得分:0)

修改:

您获得的错误是因为您没有在group by子句中包含third_party_id。

...试

select max(case when cntrctr_lcns_seq_no is null
                                   then 1
                                   else cntrctr_lcns_seq_no
                                   end) as cntrctr_lcns_seq_no
                                   from nuwmsweb.cntrctr_lcns_info
                                    where third_party_id = thirdPartyId
                                    group by third_party_id

如果您真的想将此语法用于其他(更复杂的查询)。此外,您应该在group by子句中添加third_party_id。

但是max已经忽略了null,所以这样的查询不会更能描述你想要做什么吗?

select third_party_id, max(nvl(cntrctr_lcns_seq_no,1))
        from nuwmsweb.cntrctr_lcns_info
        where third_party_id = thirdPartyId
        group by third_party_id