Monday, June 30, 2014

Need help in UPDATE data in SQL Query


CREATE TABLE test (id int identity(1,1), weeknum INT,ord int,dt1 datetime, wd int)

INSERT INTO test VALUES (101,'1','2011-12-20','484')
INSERT INTO test VALUES (null,'2','2011-02-12','444')
INSERT INTO test VALUES (null,'3','2011-02-12','444')
INSERT INTO test VALUES (null,'4','2011-02-14',NULL)
INSERT INTO test VALUES (102,'1','2013-05-27','544')
INSERT INTO test VALUES (null,'2','2013-06-02','544')
INSERT INTO test VALUES (null,'3','2013-06-03',NULL)
INSERT INTO test VALUES (null,'4','2013-06-10',NULL)
INSERT INTO test VALUES (103,'5','2013-07-08',NULL)
INSERT INTO test VALUES (null,'6','2013-07-08','690')
INSERT INTO test VALUES (null,'7','2013-07-10','690')

;with mycte as
(
SELECT id,weeknum,dt1, row_number()over(order by id DESC) rn

FROM test A)

SELECT m.id,d.weeknum , m.dt1 FROM mycte m
OUTER APPLY (SELECT TOP 1 weeknum FROM mycte
WHERE rn>= m.rn AND weeknum IS NOT NULL
ORDER BY rn ) d (weeknum )

Order by id

drop table test



No comments:

Post a Comment