更新/选择连续模式的行

时间:2018-03-03 19:14:06

标签: sql-server tsql

如何更新表格中的列以遵循特定模式? 目前我的DesiredResultAfterUpdate是空的,我想设置它,以便ID 1,2,3为1,2,3。那么下一组ID会是1,2,3(ID4,5,6和7,8,9等等)?

ID DesiredResultAfterUpdate Name
1  1                        My First Row
2  2                        My 2nd Row
3  3                        My Third Row
4  1                        My Forth Row
5  2                        My Fifth Row
6  3                        My Next Row
7  1                        My 7th Row
8  2                        etc
9  3                        etc

到目前为止,我试过

UPDATE coins set coin_Row = 1
UPDATE coins set coin_Row = 2 where coin_SortOrder%2=0
UPDATE coins set coin_Row = 3 where coin_SortOrder%3=0

仅适用于每第3项......(令人震惊)

4 个答案:

答案 0 :(得分:5)

我认为这会做你想要的,使用你的UPDATE查询作为例子:

Environment.UserInteractive

答案 1 :(得分:2)

这是怎么回事:

UPDATE  Coins
SET     Coin_Row = CASE WHEN coin_SortOrder%3 = 0 THEN 3 ELSE coin_SortOrder%3 END

答案 2 :(得分:1)

这可以让你开始对N条记录进行排名。 N设置为3以下。

CREATE TABLE TEST (ID INT)
INSERT INTO TEST
VALUES (1), (2), (3), (4), (5), (6)

WITH T AS (
SELECT 
  ID,
  RANK() OVER (ORDER BY ID) RANK
FROM 
  TEST
)
SELECT 
  ID, 
  (RANK - 1) / 3 GROUP_ID,
  ROW_NUMBER() OVER(PARTITION BY (RANK - 1) / 3 ORDER BY ID) AS ROWNUM
FROM 
  T
GROUP BY 
  ((RANK - 1) / 3), ID

答案 3 :(得分:1)

以下代码会将CoinRow中的Id列更新为1,2,3,1,2,3 ......。 Id的起始值和缺失值不会影响序列。

-- Sample data.
declare @Coins as Table ( Id Int, CoinRow Int NULL );
insert into @Coins ( Id ) values
  ( 1 ), ( 2 ), ( 3 ),
  ( 4 ), ( 6 ), ( 7 ),
  ( 10 ), ( 11 ), ( 12 ),
  ( 19 );
select * from @Coins;

-- Update the   CoinRow   column.
with CoinRows as (
  select Id, CoinRow, ( Row_Number() over ( order by Id ) - 1 ) % 3 + 1 as NewCoinRow
    from @Coins )
update CoinRows
  set CoinRow = NewCoinRow;
select * from @Coins;