从表中选择偶数行,并依次更改列值

时间:2018-07-09 12:11:27

标签: sql tsql sql-server-2012

我有一张下表,我只需要选择偶数行DocEntry,所以我正在使用查询“ select * from Test3,其中DocEntry%2 = 0”并得到它。

enter image description here

查询重用

enter image description here

结果是,我需要将DocEntry列更改为“ 1727102921”,“ 1727102922”,“ 1727102923”,“ 1727102924”,“ 1727102925”,而不是同一DocEntry。请帮助我。

2 个答案:

答案 0 :(得分:3)

尝试一下:

select 
    *
    ,min(DocEntry) over ()-1+row_number() over (order by DocEntry asc) NewDocEntry
from Test3 
where DocEntry%2 = 0

答案 1 :(得分:0)

这是我的建议

DECLARE @baseNumber int = 1727102920;
WITH #even AS (
    SELECT * FROM YourTable WHERE DocEntry % 2 = 0
)
SELECT (DocEntry - @baseNumber)/2 + @baseNumber DocEntry, Name
FROM #even

首先定义您的基数( 1727102920 ),然后将与实际“ DocEntry”和基数的差值除以二,然后将两者相加:

1727102922=> Difference: 2 => base +1 => 1727102921
1727102924=> Difference: 4 => base +2 => 1727102922
1727102926=> Difference: 6 => base +3 => 1727102923
1727102928=> Difference: 8 => base +4 => 1727102924
1727102930=> Difference: 10 => base +5 => 1727102925

这样,对于更多行,您也应该获得良好的性能。