表TB有A、B、C三个字段,现在想将从表TB1中查询的结果插入表TB的C字段,请大虾们帮帮忙
先谢谢
(SELECT e FROM(SELECT e,ct,ROW_NUMBER()OVER(ORDER BY ct DESC) rn FROM(SELECT e,COUNT (*)ct FROM TB1 GROUP BY e)t)t1 WHERE rn=1)
(SELECT e FROM(SELECT e,ct,ROW_NUMBER()OVER(ORDER BY ct DESC) rn FROM(SELECT e,COUNT (*)ct FROM TB1 GROUP BY e)t)t1 WHERE rn=2)
(SELECT e FROM(SELECT e,ct,ROW_NUMBER()OVER(ORDER BY ct DESC) rn FROM(SELECT e,COUNT (*)ct FROM TB1 GROUP BY e)t)t1 WHERE rn=3)
(SELECT e FROM(SELECT e,ct,ROW_NUMBER()OVER(ORDER BY ct DESC) rn FROM(SELECT e,COUNT (*)ct FROM TB1 GROUP BY e)t)t1 WHERE rn=4)
(SELECT e FROM(SELECT e,ct,ROW_NUMBER()OVER(ORDER BY ct DESC) rn FROM(SELECT e,COUNT (*)ct FROM TB1 GROUP BY e)t)t1 WHERE rn=5)

解决方案 »

  1.   


    declare @tb1 table (e int,col varchar(1))
    insert into @tb1
    select 1,'a' union all
    select 2,'a' union all
    select 1,'a' union all
    select 2,'a' union all
    select 3,'a' union all
    select 3,'a' union all
    select 3,'a'select e from
    (
    select e,ct,row_number()over(order by ct desc) rn from
    (select e,count (*)ct from @tb1 group by e)
    t)t1 
    where rn=1--等价于select top 1 e from @tb1 group by e order by count (*) desc
      

  2.   


    declare @tb table (a int,b int,c varchar(20))
    insert into @tb
    select 1,3,null union all
    select 2,3,null union all
    select 3,4,null union all
    select 4,5,null union all
    select 5,6,nulldeclare @tb1 table (e varchar(8),col varchar(1))
    insert into @tb1
    select 15,'a' union all
    select 20,'a' union all
    select 15,'a' union all
    select 20,'a' union all
    select 36,'a' union all
    select 36,'a' union all
    select 36,'a' union all
    select 48,'a' union all
    select 51,'a' union all
    select 51,'a' union all
    select 61,'a' update @tb set c=b.e from @tb a
    left join(
    select row_number() over (order by count (*) desc) as id, e 
    from @tb1 group by e) b on a.a=b.idselect * from @tb
    /*
    a           b           c
    ----------- ----------- --------------------
    1           3           36
    2           3           15
    3           4           20
    4           5           51
    5           6           61
    */--如果是空表直接插入的话
    insert into @tb (c)
    select e from @tb1 group by e order by count (*) desc