日期:2014-05-18  浏览次数:20500 次

给一列赋值的问题
表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)


------解决方案--------------------
SQL code

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,null

declare @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.id

select * 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