在面试过程中多次碰到两道SQL查询的题目,一是查询A(ID,Name)表中第31至40条记录,ID作为主键可能是不是连续增长的列,完整的查询语句如下:
select top 10 * from A where ID >(select max(ID) from (select top 30 ID from A order by ID) as T) order by ID
另外一道题目的要求是查询表A中存在ID重复三次以上的记录,并显示工有多少个;完整的查询语句如下:
select id, Count(*) from A group by id having count(*)>1 个数
select * from xs where id1 in (select id1 from xs group by id1 having count(*)>2 ) 数据
以上两道题目非常有代表意义,望各位把自己碰到的有代表的查询都贴上来。
分析:一:
1。select top 6 ID1 from xs order by ID1 对XS表中的前6行按ID字段进行上升排序。
2。select max(ID1) from (select top 6 ID1 from xs order by ID1)as T 查询排序后的表(6列)的最大ID
3。select top 4 * from xs where ID1 >(select max(ID1) from (select top 6 ID1 from xs order by ID1) T) order by ID1 查询当ID1大于最大ID的前4行的数据
二:
1。select id1 from xs group by id1 having count(*)>2 查询ID1重复3次的ID的值X
2。select * from xs where ID1 in (select id1 from xs group by id1 having count(*)>2) 查询ID1=X的数据
3 select distinct * from xs where id1 in(select id1 from xs group by id1 having count(*)>3) 这样就可以祛除重复值了