我有如下表:
PRODUCT COLLECTION_DATE DATA OVERRIDE
------- --------------- ---- --------
Laptop 2014/11/01 62
Laptop 2014/12/01 62 75
Laptop 2015/01/01 62
Laptop 2015/02/01 62
Laptop 2015/03/01 62 83
Laptop 2015/04/01 62
Laptop 2015/05/01 62
Laptop 2015/06/01 62
我需要使用DATA
列中的值覆盖OVERRIDE
列中的值,以生成以下数据
PRODUCT COLLECTION_DATE DATA OVERRIDE
------- --------------- ---- --------
Laptop 2014/11/01 62
Laptop 2014/12/01 75 75
Laptop 2015/01/01 75
Laptop 2015/02/01 75
Laptop 2015/03/01 83 83
Laptop 2015/04/01 83
Laptop 2015/05/01 83
Laptop 2015/06/01 83
我如何在SQL中执行此操作?先感谢您。
答案 0 :(得分:1)
您可以使用coalesce()
:
select product, collection_date, coalesce(override, data) as data, override
from table t;
您似乎想要最新的非NULL值。在Oracle 11+中,您可以使用ignore null
上的lag()
选项:
select product, collection_date,
coalesce(lag(override ignore null) over (partition by product order by collection_date), data) as data,
override
from table t;
如果您使用的是早期版本的Oracle,并且override
始终为正,则可以使用累积总和来定义具有相同值的组。然后使用它作为值:
select product, collection_date,
coalesce(max(override) over (partition by product, grp order by collection_date), data) as data,
override
from (select t.*, sum(override) over (partition by product order by collection_date) as grp
from table t
) t;