《sql中as的用法和一些经典的sql语句》由会员分享,可在线阅读,更多相关《sql中as的用法和一些经典的sql语句(3页珍藏版)》请在金锄头文库上搜索。
1、sql中 as的用法和一些经典的 sql语句2008-08-21 21:55总结一些工作中用到或碰到的 SQL语句,希望能与大家分享,同时也希望大家能提供更多的精妙 SQL语句.1、delete table1 from (select * from table2) as t2 where table1.id=t2.id2、truncate table table1 (不在事务日志中做记录,比 delete table快,但不能激活触发器)3、update table1 set column=column+1 where id=(select id from table2)4、update ta
2、ble1 set column=column+1 from table1,table2 where table1.id=table2.id5、select top n Percent * from table1 输出百分比记录6、select id,column1 * column2 as column from table1 可算明白 as的用法了7、select * from table1 where column1 like SQL#_G_O escape # 单匹配8、select table1.id from table1 where not exists (select table
3、2.id from table2 where table1.id=table2.id) 这个应该比 not in快一些9、select table1.id from table1,table2 where table1.id1 2 说明:拷贝表(拷贝数据,源表名:a 目标表名:b)SQL: insert into b(a, b, c) select d,e,f from b; 3 说明:显示文章、提交人和最后回复时间SQL: select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from ta
4、ble where table.title=a.title) b 4 说明:外连接查询(表名 1:a 表名 2:b)SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c 5 说明:日程安排提前五分钟提醒SQL: select * from 日程安排 where datediff(minute,f 开始时间,getdate()5 6 说明:两张关联表,删除主表中已经在副表中没有的信息SQL: delete from info where not exists ( select * from inf
5、obz where info.infid=infobz.infid ) 7 说明:从数据库中去一年的各单位电话费统计(电话费定额和电话费清单两个表来源)SQL: SELECT a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, yyyy) AS telyear,SUM(decode(TO_CHAR(a.telfeedate, mm), 01, a.factration) AS JAN,SUM(decode(TO_CHAR(a.telfeedate, mm), 02, a.factration) AS FRI,SUM(decode(TO_CHA
6、R(a.telfeedate, mm), 03, a.factration) AS MAR,SUM(decode(TO_CHAR(a.telfeedate, mm), 04, a.factration) AS APR,SUM(decode(TO_CHAR(a.telfeedate, mm), 05, a.factration) AS MAY,SUM(decode(TO_CHAR(a.telfeedate, mm), 06, a.factration) AS JUE,SUM(decode(TO_CHAR(a.telfeedate, mm), 07, a.factration) AS JUL,SU
7、M(decode(TO_CHAR(a.telfeedate, mm), 08, a.factration) AS AGU,SUM(decode(TO_CHAR(a.telfeedate, mm), 09, a.factration) AS SEP,SUM(decode(TO_CHAR(a.telfeedate, mm), 10, a.factration) AS OCT, SUM(decode(TO_CHAR(a.telfeedate, mm), 11, a.factration) AS NOV,SUM(decode(TO_CHAR(a.telfeedate, mm), 12, a.factr
8、ation) AS DECFROM (SELECT a.userper, a.tel, a.standfee, b.telfeedate, b.factrationFROM TELFEESTAND a, TELFEE bWHERE a.tel = b.telfax) aGROUP BY a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, yyyy) 8 说明:四表联查问题:SQL: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner
9、join d on a.a=d.d where . 9 说明:得到表中最小的未使用的 ID号SQL:SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1) THEN MIN(HandleID) + 1 ELSE 1 END) as HandleIDFROM HandleWHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a) 10 说明:模糊查询,单字匹配(短横线代表待匹配内容) select * from table where field1 like A_B_C 11 说明:as 的用法 select id,column1 * column2 as column from table1