经典sql搜集


 1、说明:显示文章、提交人和最后回复时间

  select a.title,a.username,b.adddate ,(select max(adddate) from table where table.title=a.title) adddate from table a

  2、说明:两张关联表,删除主表中已经在副表中没有的信息

  delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

3、说明:日程安排提前五分钟提醒

  SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5

  4、说明:一条sql 语句搞定数据库分页

  select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

 5、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)

  select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

 6、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表

  (select a from tableA ) except (select a from tableB) except (select a from tableC)

   7、说明:随机取出10条数据

  select top 10 * from tablename order by newid()

    8、说明:删除重复记录

   delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)

  10、说明:列出数据库里所有的表名

  select name from sysobjects where type='U' // U代表用户

 11、说明:列出表里的所有的列名

  select name from syscolumns where id=object_id('TableName')

 12、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。

  select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type

 13、说明:选择从10到15的记录

  select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

猜你喜欢

转载自www.cnblogs.com/l1pe1/p/8931709.html