1

我有一个表格,其中每一行对应于特定日期的对象价格。同一对象的不同行可以有不同日期的价格(它们将具有相同的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
4

1 回答 1

3

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

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
于 2012-05-14T15:52:16.480 回答