我正在尝试运行此查询但它失败了:
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_location
包含在group by
子句中,因为我回来的结果变得不正确。有没有办法可以在解码函数中使用product_source_location
,如上所示,而不必将其包含在group by子句中?
有趣的是我在coalesce函数中使用了product_type,并没有强迫我在group by子句中包含product_type
。
答案 0 :(得分: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
函数。
答案 1 :(得分:-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