T1
id  字段2 字段3 字段4 字段5 字段6 字段7
1     A   B     5     6   null  null
2     A   C     4     3   null  null
3     A   B     7     8   null  null
4     A   C     9     9   null  null要这个结果
id  字段2 字段3 字段4 字段5 字段6 字段7
1     A   B     5     6    12   8
2     A   C     4     3    13   9
3     A   B     7     8   null  null
4     A   C     9     9   null  null
---------------------------------------------------------------
字段6是(GROUP BY 字段2,字段3)后SUM(字段4),放在每组ID最小的那一行的字段6
字段7是(GROUP BY 字段2,字段3)后,id最大那一行的字段5,放在每组ID最小的那一行的字段7
求解

解决方案 »

  1.   

    update t1 set col6=t2.col4,col7=t2.col5
    from tb t1
    inner join (
    select a.*,b.col4,b.col5
    from  (select col2,col3,min(id) as id from tb group by col2,col3) a
    inner join (select col2,col3,sum(col4) as col4,max(col5) as col5 from tb group by col2,col3) b on a.col2=b.col2 and a.col3=b.col3
    )t2
    on t1.id=t2.id
      

  2.   


    create table #tb(id int,col2 varchar(10),col3 varchar(10),
    col4 int,col5 int,col6 int,col7 int)
    insert into #tb(id,col2,col3,col4,col5)
    select 1,'A','B',5,6
    union all select 2,'A','C',4,3
    union all select 3,'A','B',7,8
    union all select 4,'A','C',9,9select * from #tbupdate t1 set col6=t2.col4,col7=t2.col5
    from #tb t1
    inner join (
    select a.*,b.col4,b.col5
    from  (select col2,col3,min(id) as id from #tb group by col2,col3) a
    inner join (select col2,col3,sum(col4) as col4,max(col5) as col5 from #tb group by col2,col3) b on a.col2=b.col2 and a.col3=b.col3
    )t2
    on t1.id=t2.id select * from #tb
    drop table #tb/*
    1 A B 5 6 12 8
    2 A C 4 3 13 9
    3 A B 7 8 NULL NULL
    4 A C 9 9 NULL NULL
    */