I have the following data in SQL.
NAME,DATE,REF
Pat1,2021-07-15,5072
'',NULL,5072
'',NULL,5072
'',NULL,5072
'',NULL,5072
Pat2,2021-07-15,5073
Is there a way using SELECT QUERY that we can replace the NULL values in DATE column based on the REF values?
Like replace the NULL values with the first available date for matching REF value, without making any change to the database.
Expected Result
NAME,DATE,REF
Pat1,2021-07-15,5072
'',2021-07-15,5072
'',2021-07-15,5072
'',2021-07-15,5072
'',2021-07-15,5072
Pat2,2021-07-15,5073
You can do it with MAX()
window function:
SELECT NAME,
COALESCE(DATE, MAX(DATE) OVER (PARTITION BY REF)) DATE,
REF
FROM tablename
See the demo .
Have a derived table (the subquery) to return each ref's date. JOIN
:
select t1.NAME, t2.date, t1.REF
from tablename t1
join (select ref, max(date) date
from tablename
group by ref) t2
on t1.ref = t2.ref
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.