使用COALESCE处理PostgreSQL中的NULL值

时间:2014-12-15 07:26:00

标签: sql database postgresql null coalesce

我有以下查询

SELECT  DISTINCT 
     pt.incentive_marketing, 
     pt.incentive_channel, 
     pt.incentive_advertising 
FROM test.pricing pt 
WHERE pt.contract_id = 90000 
group by 1,2,3 
order by pt.incentive_marketing;

上面的查询返回o / p,如附图所示 enter image description here

但是我想使用COALESCE 将所有空值替换为0 请告诉我如何在上面的SELECT查询

中实现这一目标

现在我使用coalesce进一步修改了查询,如下所示

SELECT  
     COALESCE( pt.incentive_marketing, '0' ), 
     COALESCE(pt.incentive_channel,'0'), 
     COALESCE( pt.incentive_advertising,'0') 
FROM test.pricing pt 
WHERE pt.contract_id = 90000 
group by 1,2,3 

其结果如图2所示。

我仍然收到一行空白值

2 个答案:

答案 0 :(得分:121)

您可以将COALESCENULLIF结合使用,以获得简短有效的解决方案:

COALESCE( NULLIF(yourField,'') , '0' )
如果yourField等于第二个值(在这种情况下为''),

The NULLIF function将返回null,使COALESCE函数完全适用于所有情况:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

答案 1 :(得分:4)

如果您使用0并且空字符串''null指定未定义,则表示您遇到了数据问题。只需更新列并修复架构即可。

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

这将使加入和选择变得更加容易。