需要更新“orderby”列

时间:2016-12-08 04:01:03

标签: sql-server sql-server-2008

我有一张表test

+----+--+------+--+--+----------+--+--------------+
| ID |  | Name |  |  | orderby  |  | processgroup |
+----+--+------+--+--+----------+--+--------------+
|  1 |  | ABC  |  |  |       10 |  |            1 |
| 10 |  | DEF  |  |  |       12 |  |            1 |
| 15 |  | LMN  |  |  |        1 |  |            1 |
| 44 |  | JKL  |  |  |        4 |  |            1 |
| 42 |  | XYZ  |  |  |        3 |  |            2 |
+----+--+------+--+--+----------+--+--------------+

我想更新序列中的orderby列,我希望输出像

+----+--+------+--+--+----------+--+--------------+
| ID |  | Name |  |  | orderby  |  | processgroup |
+----+--+------+--+--+----------+--+--------------+
|  1 |  | ABC  |  |  |        1 |  |            1 |
| 10 |  | DEF  |  |  |        2 |  |            1 |
| 15 |  | LMN  |  |  |        3 |  |            1 |
| 44 |  | JKL  |  |  |        4 |  |            1 |
| 42 |  | XYZ  |  |  |        5 |  |            1 |
+----+--+------+--+--+----------+--+--------------+

这背后的逻辑是当我们将procesgroup作为1时,orderby列应更新为1,2,3,4,当procesgroup为2时,则更新orderby为5。

1 个答案:

答案 0 :(得分:-1)

这可能对您有所帮助

;WITH CTE AS (
SELECT ROW_NUMBER() OVER (ORDER BY processgroup, ID ) AS SNO, ID FROM TABLE1
)
UPDATE TABLE1 SET TABLE1.orderby= CTE.SNO FROM CTE WHERE TABLE1.ID = CTE.ID