计算SQL Server数据库中的列

时间:2013-02-25 07:18:04

标签: sql sql-server tsql sql-update

我有这样的表

 id buildingId order  title
 --------------------------
  1      2      null  test1
  2      2      null  test2
  3      2      null  test3
  4      3      null  test4
  5      3      null  test5
  6      5      null  test6

我需要为每一行计算订单价值。我需要在执行sql查询后获取此表

 id buildingId order  title
  1      2      0     test1
  2      2      1     test2
  3      2      2     test3
  4      3      0     test4
  5      3      1     test5
  6      5      0     test6

我该怎么做?

1 个答案:

答案 0 :(得分:1)

WITH recordList
AS
(
    SELECT  ID, buildingID, [order], title,
            ROW_NUMBER() OVER (PARTITION BY buildingID
                                ORDER BY ID) rn
    FROM    tableName
)
UPDATE recordList
SET [order] = rn - 1