我从有零售和公司客户的桌子中选择。我希望我的结果集在一列中返回企业和零售客户的名称。目前,我在以下两个不同的列中返回它们:
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;我想要做的事情是可能的吗?我怎样才能做到这一点,而不需要返回一个不同的零售专栏和另一个企业客户的专栏呢?
发布于 2013-08-08 13:00:45
如果只填充了这两个字段中的一个,那么返回作为单个列填充的任何字段都非常简单:
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_idcoalesce返回它遇到的第一个非空值。
我不知道查询中聚合的意义是什么,所以我忽略了这一点。
作为脚注,在甲骨文中,nvl的表现与coalesce非常相似,具有以下重要区别:
nvl只接受两个参数,而合并可以接受n个参数。nvl将计算其所有参数,但coalesce将按顺序对每个参数进行计算,在达到非零值时停止(换句话说,coalesce将使用短路评估,而nvl不会)。这在很大程度上是很重要的,因为您经常会看到nvl用于类似的目的。
发布于 2013-08-08 13:05:19
按下面的方式编写查询,您可以在一列中获得两个cust_name
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 发布于 2013-08-08 12:59:27
是的,您可以使用UNION (过滤掉重复的)或UNION ALL (不使用)。
例如:
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或者COALESCE,就像艾伦说的。这取决于您是否想使用其中一种或另一种(然后使用coalesce),或者是否希望在同一列中组合实体(使用UNION)。
https://stackoverflow.com/questions/18126618
复制相似问题