Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

help required for complex query

$
0
0

hi guys

 
i need your help to write sql query where i need to fill null values when they are in between as you can see the same data is for 2 ids... i am able to fill null value for id 101 as it is the last one with the sql query provided below.. but not able to do same with when null values are in between...

 
for id 102, if null value row date is greater or equal to previous row date then fill null value with previous row... and if like in case where ord ='5' there date is equal to next row date then i need to fill it with next row wd value..

using sql server 2005

 
Let me know if you need more information:-

 
 
CREATE TABLE tt (id INT,ord int,dt1 datetime, wd int)

INSERT INTO tt VALUES (101,'1','2011-12-20','484')
INSERT INTO tt VALUES (101,'2','2011-02-12','444')
INSERT INTO tt VALUES (101,'3','2011-02-12','444')
INSERT INTO tt VALUES (101,'4','2011-02-14',NULL)

 
INSERT INTO tt VALUES (102,'1','2013-05-27','544')
INSERT INTO tt VALUES (102,'2','2013-06-02','544')
INSERT INTO tt VALUES (102,'3','2013-06-03',NULL)
INSERT INTO tt VALUES (102,'4','2013-06-10',NULL)
INSERT INTO tt VALUES (102,'5','2013-07-08',NULL)
INSERT INTO tt VALUES (102,'6','2013-07-08','690')
INSERT INTO tt VALUES (102,'7','2013-07-10','690')

 
select * from tt

/********************************************/

Result expected

CREATE TABLE  (id INT,ord int,dt1 datetime, wd int)

INSERT INTO tt_result VALUES (101,'1','2011-12-20','484')
INSERT INTO tt_result VALUES (101,'2','2011-02-12','444')
INSERT INTO tt_result VALUES (101,'3','2011-02-12','444')
INSERT INTO tt_result VALUES (101,'4','2011-02-14','444')

INSERT INTO tt_result VALUES (102,'1','2013-05-27','544')
INSERT INTO tt_result VALUES (102,'2','2013-06-02','544')
INSERT INTO tt_result VALUES (102,'3','2013-06-03','544')
INSERT INTO tt_result VALUES (102,'4','2013-06-10','544')
INSERT INTO tt_result VALUES (102,'5','2013-07-08','690')
INSERT INTO tt_result VALUES (102,'6','2013-07-08','690')
INSERT INTO tt_result VALUES (102,'7','2013-07-10','690')

 
select * from tt_result

 

SELECT isnull(wd, FINAL_WD) F_wd,* FROM
(
select *,
FINAL_WD = (SELECT top 1 b.wd
                                 FROM     #t b
                                 WHERE    b.id = a.id
                                     and b.ord + 1 = a.ord
                                    
                                 ORDER    BY b.ord desc)
FROM     #t a
WHERE    a.wd is null
) D

 






Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>