2011-03-07 58 views
0
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。但是我得到錯誤「不是一個小組小組條款」。甲骨文 - 最大案例

此選擇語句是較大插入的一部分。

謝謝!

更新:這是整個聲明

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); 

回答

1

MAX聚合函數忽略空值,所以你不需要用你想要的最大值在整個返回集case語句或組。

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

不完全,我實際上想要1返回,如果表中還沒有一個id。 – kralco626 2011-03-07 14:59:00

+0

夠公平,只需將它包裹在一起。看我的編輯。 – 2011-03-07 15:04:28

+0

不確定什麼樣的coalsce ......但是它起作用,如果我從nuwmsweb.cntrctr_lcns_info中選擇coalesce(max(cntrctr_lcns_seq_no)+ 1,1)作爲cntrctr_lcns_seq_no,其中third_party_id = thirdPartyId'注意我試過的'+ 1' – kralco626 2011-03-08 11:21:44

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 
+0

但我得到一個不能插入到錯誤。換句話說,當這個ID還沒有出現在表中時,這是返回null比1 – kralco626 2011-03-07 15:00:37

+0

@ kralco626:你對你的意思是「你不能插入錯誤」?你在聲明中沒有'INSERT'。你正在執行的查詢的其餘部分是什麼? – Lamak 2011-03-07 15:02:55

0

編輯:

你所得到的錯誤是因爲你不包括group by子句中third_party_id。

的Try ...

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已經忽略了空值,所以這樣的查詢不會更能描述你正在做什麼嗎?

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 
+0

雅我喜歡那樣。我必須做一些其他的錯誤,因爲我一直得到一個不能插入空錯誤 – kralco626 2011-03-07 15:03:51

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的​​3210如果您願意)。