在dense_rank查询期间忽略空值

时间:2012-05-14 15:16:36

标签: sql oracle

我有一张表,其中每一行对应于特定日期对象的价格。 不同的行可以为同一对象的不同日期定价(它们将具有相同的object_ids字段) 我试图在单个查询中获取包含每个对象的最新价格的行,如下所示:

SELECT
   MAX(price1) KEEP (DENSE_RANK FIRST
ORDER BY day DESC),
MAX(price2) KEEP (DENSE_RANK FIRST
ORDER BY day DESC)

FROM historic_prices H3
GROUP BY object_ids;

不幸的是,当最新价格为NULL并且它只返回NULL时,这不起作用...有没有办法忽略空值?我找不到任何东西。 感谢

编辑: 基本上我想做以下事情:

table:

col 1 | col 2 | obj_id | date
----------------------------
null  | null  |   1    |  100
----------------------------
5     | null  |   1    |  90
---------------------------
3     | null  |   0    |  80
-----------------------------
7     |  4    |   1    |  70


result : 

col 1 | col 2 | obj_id |
-------------------------
5     | 4     | 1
---------------------
3     | null  | 0

1 个答案:

答案 0 :(得分:3)

如果您使用的是10g +,则可以使用分析函数FIRST_VALUEIGNORE NULLS子句:

SELECT DISTINCT 
       object_ids, 
       FIRST_VALUE(price1 IGNORE NULLS)
          OVER (PARTITION BY obj_id ORDER BY DAY DESC
                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) p1, 
       FIRST_VALUE(price2 IGNORE NULLS) 
          OVER (PARTITION BY obj_id ORDER BY DAY DESC
                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) p2
  FROM historic_prices;

这适用于9iR2(至少包含您的数据集):

SQL> WITH DATA AS (
  2     SELECT NULL col1, NULL col2, 1 obj_id, 100 DAY FROM dual
  3     UNION ALL SELECT 5, NULL, 1, 90 FROM dual
  4     UNION ALL SELECT 3, NULL, 0, 80 FROM dual
  5     UNION ALL SELECT 7, 4, 1, 70 FROM dual
  6  )
  7  SELECT obj_id,
  8         MAX(col1)
  9            KEEP (DENSE_RANK FIRST ORDER BY DECODE(col1, NULL, 1, 0),
 10                                            DAY DESC) last_price1,
 11         MAX(col2)
 12            KEEP (DENSE_RANK FIRST ORDER BY DECODE(col2, NULL, 1, 0),
 13                                            DAY DESC) last_price2
 14    FROM DATA
 15   GROUP BY obj_id;

    OBJ_ID LAST_PRICE1 LAST_PRICE2
---------- ----------- -----------
         0           3 
         1           5           4