Reputation: 4150
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?
Upvotes: 2
Views: 444
Reputation: 17429
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:
nvl
only takes 2 parameters, whereas coalesce can take n parametersnvl
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.
Upvotes: 5
Reputation: 560
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
Upvotes: 4
Reputation: 22915
Yes, you can use a UNION
(which filters out duplicates) or UNION ALL
(which does not).
e.g.
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
).
Upvotes: 3