简体   繁体   中英

Different table fields in one result set Oracle

I am selecting from tables that have retail and corporate customers. I want My result set to return the names of both corporate and retail customers in one column. Currently I am returning them in two different columns like this:

select e.cust_id, 
       e.cust_location, 
       f.location
       max(case 
             when e.preferredname is not null 
             then e.preferredname 
           end
          )RETAIL_CUST_NAME,
       max(case 
             when e.preferredname is null 
             then e.CORP_NANME 
           end 
          )CORPORATE_CUST_NAME 
  from Mytable e, 
       myothertable f 
 where e.cust-id = f.cust_id
 group by e.cust_id, 
       e.cust_location, 
       f.location, 
       e.preferredname, 
       e.corp_name;

Is what I am trying to do Possible and How Can I achieve this without having to return a different column for retail and another for corporate customer?

If only one of the two fields is ever populated, then returning whichever is populated as a single column is pretty simple:

select e.cust_id, 
      e.cust_location, 
      f.location
      coalesce(e.preferredname, e.CORP_NANME) as CUST_NAME,
from Mytable e
     join myothertable f on e.cust_id = f.cust_id

coalesce returns the first non-null value it encounters.

I'm not sure what the point of the aggregate in your query is, so I left that out.


As a footnote, in Oracle, nvl performs very similarly to coalesce , with these important distinctions:

  1. nvl only takes 2 parameters, whereas coalesce can take n parameters
  2. when functions or equations are pass into them as parameters, nvl will evaluate all of its parameters, but coalesce will evaluate each in order, stopping when it reaches a non-null value (in other words, coalesce will use short-circuit evaluation, but nvl will not).

This is mostly significant because you'll often see nvl used for a similar purpose.

Write query as below and you can get both cust_name in one column

select e.cust_id, 
   e.cust_location, 
   f.location
   max(case 
         when e.preferredname is not null 
         then e.preferredname 
       Whene preferredname is null 
         then e.CORP_NANME 
       end 
      )CUST_NAME 

Yes, you can use a UNION (which filters out duplicates) or UNION ALL (which does not).

eg

select 
case when e.preferredname is not null then e.preferredname end 
as RETAIL_CUST_NAME,
from Mytable e
union all
select case when e.preferredname is null then e.CORP_NANME end 
from Mytable e

Or COALESCE , as Allan says. Depends a bit if you want to use one or the other (then use coalesce ) or if you want to combine entities in the same column (use UNION ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM