读书人

求解面试时sql语句有关问题答案

发布时间: 2012-01-11 22:28:46 作者: rapoo

求解面试时sql语句问题答案!
1.一个表(表a),里面有十条数据,这十条数据都是相同的,现要删除其中九条。请问怎么写sql语句?

2.一个表,表名为table,里面有n条数据。例如下表:
id name data
1 a 123
2 b 123
...
...
23 a 234
...
32 b 345
....
....
name为a的数据共有n条,name为b的数据共有m条,请问怎么写sql语句使查询a时,能够统计a的数量?
结果类似于:
name count
a n




[解决办法]
1.select top 1 * into # from a
go
truncate table a
go
insert a select * from #
或者
select distinct * into tb_tmp from a
go
drop table a
go
exec sp_rename 'tb_tmp ', 'a '
2.select name,[count]=count(*) from a group by name
或者
select name,[count]=(select count(*) from a where name=b.name) from a b
[解决办法]
第一题:
declare @i int
set @i=1
while(@i <9)
begin
delete from dbo.表 where id=@i
set @i=@i+1
end

第二题:
select count(*) as count
from dbo.table
where name= 'a '
group by name

读书人网 >SQL Server

热点推荐