我有一个名为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 |
是否可以按顺序更新Seat_No中的数字,从1到最后一个座位号计数,其等级no等于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放入查询的情况下解决这个问题?请帮助。
答案 0 :(得分: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
答案 1 :(得分: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