oracle11g - SQL aggregate function to return single value if there is only one, otherwise null -


i'm looking best way achieve aggregate function this:-

  • if group contains single repeated value, return value
  • if group contains nulls, return null
  • if group contains more 1 value, return null

here's sample data:

create table example ( id  number(3),   val varchar2(3));  insert example values (1,'a'); insert example values (2,'a'); insert example values (2,'b'); insert example values (3,null); insert example values (3,'a'); insert example values (4,'a'); insert example values (4,'a'); 

the sql should like:-

select id, ????( val ) only_val example  group id order id 

the result after should this:-

 id       only_val   1         2          3          4       

in real thing, want on multiple val columns (grouped same id). there several hundred records per id.

i thought interesting problem solution have mess of nvl, min , max , seems there should neater way.

will work for original data?

select  id,          case when count(distinct val) = 1 , count(id) = count(val)              max(val)              else null         end only_val    example group   id order   id 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -