急~!求一句sql语句!在线等~!谢谢!!!!!!!!
有两个表a、b
a表字段(a1,a2,a3)均为varchar(22)
b表字段(b1 int,b2 varchar(22))
问题:
把b表中的数据根据b1进行排序,取前三条数据插入表a
如:
表b b1 b2
---- -----
34 b
78 bb
98 bbb
根据降序排序后写入表a
a1 a2 a3
--- --- ---
bbb bb b
谢谢~!
------解决方案--------------------create table a(
a1 varchar(22),a2 varchar(22),a3 varchar(22)
)
create table b(
b1 int,
b2 varchar(22)
)
insert into b
select 34, 'b ' union all
select 78, 'bb ' union all
select 98, 'bbb '
declare @b varchar(100),@s varchar(200)
set @b= ' '
select top 3 @b=@b+ ', ' ' '+b2+ ' ' ' ' from b order by b1
set @b=stuff(@b,1,1, ' ')
set @s= 'insert into a select '+@b
exec(@s)
select * from a
drop table a
drop table b
------解决方案--------------------Create Table a(a1 varchar(22), a2 varchar(22),a3 varchar(22))
Create Table b(b1 int, b2 varchar(22))
Insert b Select 34, 'b '
Union All Select 78, 'bb '
Union All Select 98, 'bbb '
GO
Insert a
Select TOP 1 b2,
(Select TOP 1 b2 From b Where b1 < T.b1 Order By b1 Desc),
(Select TOP 1 b2 From b Where b1 Not In (Select TOP 2 b1 From b Order By b1 Desc) Order By b1 Desc) From b T Order By b1 Desc
Select * From a
GO
Drop Table a, b
--Result
/*
a1 a2 a3
bbb bb b
*/
------解决方案--------------------create table a(a1 varchar(22),a2 varchar(22),a3 varchar(22))
create table b(b1 int,b2 varchar(22))
insert into b select 34, 'b '
insert into b select 78, 'bb '
insert into b select 98, 'bbb '
insert into a
Select TOP 1 b2 as a1,
(Select TOP 1 b2 From b Where b1 < T.b1 Order By b1 Desc) as a2,
(Select TOP 1 b2 From b Where b1 <T.b1 order by b1) as a3
From b T Order By b1 Desc
select * from a
drop table a,b
a1 a2 a3
---------------------- ---------------------- ----------------------
bbb bb b
(1 行受影响)