我在表格中有以下数据
col1 col2 col3
276328 | 999999999999 | 664116
927356 | 999999999999 | 664140
927356 | 999999999999 | 664140
927356 | 999999999999 | 664159
927379 | 999999999999 | 664172
代码:
create table #table (col1 bigint, col2 bigint, col3 bigint)
insert into #table values(276328, 999999999999, 664116)
insert into #table values(927356, 999999999999, 664140)
insert into #table values(927356, 999999999999, 664140)
insert into #table values(927356, 999999999999, 664159)
insert into #table values(927379, 999999999999, 664172)
我需要将Col2更新为Col3中的值,同时对col1进行分组并选择Min(col1)以应用于该子组。
276328和927379属于他们自己的群组,但927356是需要将最低col3编号分配给col2的群组
因此,上面的表格已经更新应该如下所示:
col1 | col2 | col3
276328 | 664116 | 664116
927356 | 664140 | 664140
927356 | 664140 | 664140
927356 | 664140 | 664159
927379 | 664172 | 664172
我有2m +行要更新,所以它必须是批量更新而不是循环。
如何编写SQL来更新表?
答案 0 :(得分:3)
declare @myTable table (col1 bigint, col2 bigint, col3 bigint)
insert @myTable
select 276328 , 999999999999 , 664116
union select 927356 , 999999999999 , 664140
union select 927356 , 999999999999 , 664140
union select 927356 , 999999999999 , 664159
union select 927379 , 999999999999 , 664172
update a
set a.col2 = b.col3
from @myTable a
inner join
(
select col1, MIN(col3) col3
from @myTable
group by col1
) b
on a.col1 = b.col1
select * from @myTable
答案 1 :(得分:0)
update t
set col2 = g.mincol3
from tbl t
join (
select col1, min(col3) mincol3
from tbl
group by col1
) g on t.col1 = g.col1
答案 2 :(得分:0)
如果您使用MySQL
UPDATE table1 a
INNER JOIN
(
SELECT col1, minCol
FROM
(
SELECT col1, MIN(col3) minCol
FROM tableName
GROUP BY col1
) c
) b ON a.col1 = b.col1
SET a.col2 = b.minCol
答案 3 :(得分:0)
如果您的RDBMS SQLServer2005 +
UPDATE x
SET x.col2 = x.col3
FROM (SELECT col2, MIN(col3) OVER (PARTITION BY col1) AS col3
FROm #table) x