我有一个查询返回avg(price)
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(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.
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查询的示例:
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
IMHOCOALESCE不应与之一起使用,AVG因为它会修改值。NULL意味着未知,别无其他。这不像是在中使用它SUM。在此示例中,如果我们替换AVG为SUM,则结果不会失真。将总和加0不会对任何人造成伤害,但是对于未知值计算平均值为0时,您不会获得真实的平均值。
AVG
NULL
SUM
在那种情况下,我将添加price IS NOT NULLinWHERE子句以避免这些未知值。
price IS NOT NULL
WHERE