如果返回值为null,postgresql返回0
我有一个查询返回平均(价格)
select avg(price) from( select *, cume_dist() OVER (ORDER BY price desc) from web_price_scan where listing_Type='AARM' and u_kbalikepartnumbers_id = 1000307 and (EXTRACT(Day FROM (Now()-dateEnded)))*24 < 48 and price>( select avg(price)* 0.50 from(select *, cume_dist() OVER (ORDER BY price desc) from web_price_scan where listing_Type='AARM' and u_kbalikepartnumbers_id = 1000307 and (EXTRACT(Day FROM (Now()-dateEnded)))*24 < 48 )g where cume_dist < 0.50 ) and price<( select avg(price)*2 from( select *, cume_dist() OVER (ORDER BY price desc) from web_price_scan where listing_Type='AARM' and u_kbalikepartnumbers_id = 1000307 and (EXTRACT(Day FROM (Now()-dateEnded)))*24 < 48 )d where cume_dist < 0.50) )s having count(*) > 5
如果没有值可用,如何使它返回0?
使用coalesce
COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.
用你的查询编辑COALESCE的例子:
SELECT AVG( price ) FROM( SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan WHERE listing_Type = 'AARM' AND u_kbalikepartnumbers_id = 1000307 AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48 AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50 FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan WHERE listing_Type='AARM' AND u_kbalikepartnumbers_id = 1000307 AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48 ) g WHERE cume_dist < 0.50 ) AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2 FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc ) FROM web_price_scan WHERE listing_Type='AARM' AND u_kbalikepartnumbers_id = 1000307 AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48 ) d WHERE cume_dist < 0.50) )s HAVING COUNT(*) > 5
恕我直言, COALESCE
不应该与AVG
一起使用,因为它修改了这个值。 NULL
意味着不知道,没有别的。 这不像在SUM
使用它。 在这个例子中,如果我们用SUM
replaceAVG
,结果不会失真。 给总和加0不会伤害任何人,只要计算未知值的平均值为0,就不会得到真正的平均值。
在这种情况下,我会在WHERE
子句中添加price IS NOT NULL
来避免这些未知的值。
正如Luc M所build议的那样,使用coalesce。
$ create table foo (bar int); CREATE TABLE $ select avg(bar) from foo; avg ----- (1 row) $ select coalesce(avg(bar), 0) from foo; coalesce ---------- 0 (1 row) $ insert into foo values (3); INSERT 0 1 $ insert into foo values (9); INSERT 0 1 $ select coalesce(avg(bar), 0) from foo; coalesce -------------------- 6.0000000000000000 (1 row)
当然,“从foo”可以被“从……(这里任何复杂的逻辑…)取代为foo”