postgresql return 0 if returned value is null

后端 未结 3 1233
失恋的感觉
失恋的感觉 2021-01-30 12:32

I have a query that returns avg(price)

  select avg(price)
  from(
      select *, cume_dist() OVER (ORDER BY price desc) from web_price_scan
      where listing         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 12:59

    use 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.
    

    Edit

    Here's an example of COALESCE with your query:

    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
    

    IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

    In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

提交回复
热议问题