I have table like below :
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
I need to override the values in DATA
column with the values from OVERRIDE
column to produce below data
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
How can I do that in SQL? Thank you in advance.
You can do this in a single row using coalesce()
:
select product, collection_date, coalesce(override, data) as data, override
from table t;
You seem to want the most recent non-NULL value. In Oracle 11+, you can use the ignore null
option on 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;
If you are using an earlier version of Oracle, and override
is always positive, you can take the cumulative sum to define groups with the same value. Then use this for the value:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.