0

我有一个名为 class 的表

|Record_No [PK] | Student_No  | Class_No  | Seat_No  |
=====================================================
|1              | 200910      | 2         | 20       |
|2              | 201234      | 2         | 13       |
|3              | 200965      | 2         | 1        |
|4              | 200920      | 2         | 8        |
|5              | 200911      | 2         | 9        |
|6              | 200955      | 1         | 10       |
|7              | 200924      | 1         | 9        |
|8              | 200922      | 1         | 1        |
|9              | 200901      | 2         | 11       |
|10             | 200902      | 2         | 18       |

是否可以按从 1 到最后一个座位号的顺序更新座位号中的数字,其中座位号的等级等于 2?

该表应如下所示:

|Record_No [PK] | Student_No  | Class_No  | Seat_No  |
=====================================================
|1              | 200910      | 2         | 1        |
|2              | 201234      | 2         | 2        |
|3              | 200965      | 2         | 3        |
|4              | 200920      | 2         | 4        |
|5              | 200911      | 2         | 5        |
|6              | 200955      | 1         | 10       |
|7              | 200924      | 1         | 9        |
|8              | 200922      | 1         | 1        |
|9              | 200901      | 2         | 6        |
|10             | 200902      | 2         | 7        |

截至目前,我只能通过使用来实现这一点

UPDATE class SET Seat_No = 1 WHERE Class_No = 2 AND Student_No = 200910;
UPDATE class SET Seat_No = 2 WHERE Class_No = 2 AND Student_No = 201234;
...

等等..

如果不将每个 student_no 都放在查询中,我该如何解决这个问题?请帮忙。

4

2 回答 2

2
update class
set seat_no = s.rn
from (
    select
        row_number() over(order by record_no) rn,
        record_no
    from class
    where class_no = 2
) s
where class.record_no = s.record_no

如果要更新所有类:

update class
set seat_no = s.rn
from (
    select
        row_number() over(partition by class_no order by record_no) rn,
        record_no
    from class
) s
where class.record_no = s.record_no
于 2013-02-26T17:09:18.007 回答
1

假设您的 Record_No 在您的示例中为 1-5,您可以使用它:

UPDATE class SET Seat_No = Record_No WHERE Class_No = 2

如果不是,则取决于您的 RDBMS。

这是postgresql方法:

UPDATE  Class C
SET     Seat_No = t.rn
FROM    (
       SELECT Record_No, ROW_NUMBER() OVER (ORDER BY Record_No) rn
        FROM Class
       WHERE Class_no = 2
        ) t
WHERE   C.Record_No = t.Record_No

SQL 小提琴演示

于 2013-02-26T17:02:51.317 回答