1

我在表格中有以下数据

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 来更新表?

4

4 回答 4

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
于 2012-10-25T00:19:08.020 回答
0

如果您的关系型数据库 SQLServer2005+

UPDATE x
SET x.col2 = x.col3
FROM (SELECT col2, MIN(col3) OVER (PARTITION BY col1) AS col3
      FROm #table) x
于 2012-10-25T06:33:59.513 回答
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
于 2012-10-25T00:14:26.400 回答
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
于 2012-10-25T00:28:00.313 回答