简体   繁体   English

根据分组更新表中的行

[英]Update rows in a table based on grouping

I have a table with records of the same type with ID's and a grouping.我有一个表,其中包含具有 ID 和分组的相同类型的记录。 I need to update the id's of table 1 into table 2 based on the record id from largest to smallest using the position.我需要使用 position 根据从最大到最小的记录 id 将表 1 的 id 更新到表 2 中。

Table 1表格1

ID ID Group团体 Name姓名
1 1 A一个 Apple苹果
2 2 A一个 Apple苹果
3 3 B Apple苹果
4 4 B Apple苹果

Table 2表 2

ID ID recordid记录ID position position group团体
1 1 1 1 250 250 A一个
2 2 2 2 350 350 A一个
3 3 null null 450 450 A一个
4 4 null null 550 550 A一个
5 5 3 3 250 250 B
6 6 4 4 350 350 B
7 7 null null 450 450 B
8 8 null null 550 550 B
update table2
set recordid=T1.ID
From Table1 T1
join Table2 T2 on T2.Group=T1.Group

This isn't distinct so I don't think it's right, but I can't figure it out.这并不明显,所以我认为它不正确,但我无法弄清楚。 where?????在哪里?????

the problem is you have multiple Id per group, so you have to choose one:问题是您每个组有多个 Id,因此您必须选择一个:

update table2
set recordid= ( select top 1 T1.ID
                From Table1 T1
                join Table2 T2 on T2.Group=T1.Group
               )
where recordid is null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM