您好我想添加/值分配給行已爲空在SQL服務器上一行價值2005添加/值分配給行已爲空與上一行值
例子:
Col1 Col2
1 45
NULL 30
2 20
3 40
NULL 30
NULL 20
4 40
輸出必須是這樣的
Col1 Col2
1 45
1 30
2 20
3 40
3 30
3 20
4 40
您好我想添加/值分配給行已爲空在SQL服務器上一行價值2005添加/值分配給行已爲空與上一行值
例子:
Col1 Col2
1 45
NULL 30
2 20
3 40
NULL 30
NULL 20
4 40
輸出必須是這樣的
Col1 Col2
1 45
1 30
2 20
3 40
3 30
3 20
4 40
我假設你有一個名爲id
列是一個主鍵,或者您的默認順序由這一領域取得,我假設你的表名是t1。
這裏是它給你需要的結果查詢:
SELECT * FROM T1
WHERE col1 IS NOT NULL
UNION ALL
SELECT a.id, nested.col1, a.col2 FROM t1 as a
CROSS APPLY
(SELECT TOP 1 * FROM t1 as b WHERE a.id > b.id and b.col1 IS NOT NULL ORDER BY b.id DESC) nested
WHERE a.col1 IS NULL
ORDER BY id
感謝它與您的解決方案 – Prabu
除非有表中的另一列(S)來決定順序,它不能做
有沒有在沒有ORDER BY的SQL中保證了訂單。所以我們不知道哪個NULL會從數據庫中讀取數據的位置或順序。
需要ORDER BY來保證任何順序,數據將首先帶有NULL,然後帶有填充行。如果沒有ORDER BY一個SELECT不會在您的預期順序返回上面行,那麼它是巧合只有
declare @table as table(Col1 int,Col2 int)
insert into @table values(1,45)
insert into @table values(NULL,30)
insert into @table values(2,20)
insert into @table values(3,40)
insert into @table values(NULL,30)
insert into @table values(NULL,20)
insert into @table values(4,40)
select * from @table
while exists(select 1 from @table where Col1 is null)
begin
update t1 set t1.Col1=t2.Col1 from
(select ROW_NUMBER() over(order by (select 0)) as RowNo,Col1
from @table)as t1 cross apply
(select top 1 * from (select ROW_NUMBER() over(order by (select 0)) as RowNo,Col1
from @table)as t
where t.RowNo<t1.RowNo order by RowNo desc)t2 where t1.Col1 is null
end
select * from @table
此查詢適用於你,如果你不關心的性能!
感謝,查詢工作正常,我需要考慮性能也在這裏。 – Prabu
你也可以; 'over(order by(select 0))'這將適用於相同的「排序」作爲選擇沒有訂單 –
@亞歷K感謝您的建議,我編輯了我的答案。它比'over(rand())'更好的性能 – NaveenBhat
表中是否有其他信息來決定訂單? – gbn