0

我正在尝试运行此查询,但它失败了:

select p.product_id, p.product_name, 
 cast(collect(coalesce(product_type, decode(product_description,null,'DESCR' || '-' product_description) as my_type) as product_type,
 decode(product_source_location, null, 'NO_SOURCE', product_source_location)
from products
group by p.product_id, p.product_name

它失败了,因为product_source_location它不是 group by 子句的一部分。

我不想包含product_source_locationgroup by子句中,因为我得到的结果变得不正确。有没有一种方法可以product_source_location在如上所示的 decode 函数中使用,而不必将其包含在 group by 子句中?

有趣的是,我在 coalesce 函数中使用 product_type,它不会强迫我将其包含product_type在 group by 子句中。

4

2 回答 2

4

尝试这样做:

coalesce(max(product_source_location), 'NO_SOURCE')

复杂的collect语句是正确的,因为collect是一个聚合函数。group by最终解码使用的是子句中未提及的列。这通过环绕max()它来解决问题。

而且,您可以使用以下方法执行此操作decode()

decode(max(product_source_location), NULL, 'NO_SOURCE', max(product_source_location))

但我鼓励你学习更标准的coalesce()函数和case函数。

于 2013-02-14T13:23:19.277 回答
-1

你不能只使用 DISTINCT 吗?像这样:

select DISTINCT p.product_id, p.product_name, 
 cast(collect(coalesce(product_type, decode(product_description,null,'DESCR' || '-' product_description) as my_type) as product_type,
 decode(product_source_location, null, 'NO_SOURCE', product_source_location)
from products
于 2013-02-14T13:30:51.490 回答