精妙SQL语句收集

合集下载

sql 高级语句

sql 高级语句

sql 高级语句1. 哎呀,你知道吗?SQL 高级语句就像是一把神奇的钥匙,能打开数据库的神秘宝藏!比如说,当你想从海量数据中快速筛选出特定条件的数据,像从一堆糖果中挑出你最爱的口味,用 `WHERE` 子句就能轻松搞定!你难道不想拥有这样的神奇能力?2. 嘿,朋友!SQL 高级语句简直是数据分析的超级武器!就好比你在战场上,有了它就能精准打击目标。

像 `JOIN` 操作,能把不同表的信息整合起来,这不就像把拼图碎片拼成完整的画面吗?你不想试试?3. 哇塞!SQL 高级语句可太牛啦!它就像一个魔法棒,能让数据乖乖听话。

比如说 `GROUP BY` 语句,能把数据分组统计,这难道不像把一群小伙伴按照特点分类吗?是不是很神奇?4. 亲,SQL 高级语句那可是高手必备的技能!比如说 `HAVING` 子句,它能在分组后进行筛选,这感觉就像在一堆整理好的物品中再挑出精品,你难道不心动?5. 哎呀呀,SQL 高级语句简直是数据世界的主宰!像 `ORDER BY` 能让数据按你想要的顺序排列,这不就跟给调皮的孩子排好队一样简单吗?你还不赶紧掌握?6. 嘿!SQL 高级语句可是个大宝贝!比如说`SUBQUERY` 子查询,能在一个查询中嵌套另一个查询,这就像在一个大盒子里装着小盒子,充满惊喜!难道你不好奇?7. 哇哦!SQL 高级语句厉害得不要不要的!比如 `UNION` 操作,能把多个查询结果合并,这难道不像把几条小溪汇聚成一条大河?你不想试试看?8. 亲呐,SQL 高级语句就是通往数据巅峰的捷径!像 `DISTINCT` 关键字,能去除重复数据,这感觉就像把杂物清理掉只留下精华,是不是很棒?9. 哎呀,SQL 高级语句太让人惊叹了!比如说 `INDEX` 索引,能大大提高查询速度,这就像给你的赛车装上超强引擎,难道不酷?10. 嘿哟,SQL 高级语句简直是无敌的存在!像 `CASE WHEN` 语句,能实现灵活的条件判断,这不就跟你在做复杂的选择题时有了标准答案一样吗?你还在等什么?11. 哇噻!SQL 高级语句可真是妙不可言!比如说 `LIMIT` 限制行数,能只获取你需要的部分数据,这难道不像在一大桌美食中只挑你最想吃的那几样?是不是很实用?12. 亲呀,SQL 高级语句那是相当厉害!比如 `OFFSET` 偏移量,能跳过一些数据开始获取,这感觉就像在一本书中跳过前面的章节直接从中间开始读,你不想体验下?13. 哎呀妈呀,SQL 高级语句太牛掰了!像 `CTE` 公共表表达式,能把复杂的查询分解成多个部分,这难道不像把一个大任务分解成小步骤逐个完成?是不是很聪明?14. 嘿,SQL 高级语句绝对是数据处理的神器!比如说`ROW_NUMBER` 函数,能给每行数据编号,这就像给每个士兵都贴上了专属标签,难道不厉害?15. 哇啦哇啦,SQL 高级语句厉害炸了!比如`PIVOT` 行转列操作,能把数据的结构进行转换,这难道不像给房子重新装修换个风格?你不想尝试下?16. 亲哟,SQL 高级语句那可是神一般的存在!像 `MERGE` 合并操作,能根据条件更新或插入数据,这感觉就像给两个团队合并并安排好每个人的位置,是不是很强大?17. 哎呀喂,SQL 高级语句太让人佩服了!比如说 `WINDOW FUNCTIONS` 窗口函数,能对数据进行分区计算,这难道不像把一个大蛋糕切成小块分别计算?是不是很有趣?18. 嘿呀,SQL 高级语句简直绝绝子!像 `CROSS APPLY` 和`OUTER APPLY` ,能关联表并获取相关数据,这就像两个好朋友手牵手分享彼此的秘密,难道不吸引人?19. 哇哈哈,SQL 高级语句太厉害了吧!比如说 `XML and JSON functions` ,能处理 XML 和 JSON 格式的数据,这难道不像拥有了能读懂各种语言的超能力?你不想拥有吗?20. 亲呐亲,SQL 高级语句就是数据世界的王者!像 `Full-text Search` 全文搜索,能快速找到你想要的文本,这感觉就像在茫茫书海中瞬间找到你渴望的那一页,是不是超棒?。

精妙SQL语句介绍(大全)

精妙SQL语句介绍(大全)
说明:查询从第30条到第40条的记录数
SQL:select top 10 * from temp where id not in (select top 30 id from temp order by id asc) order by id asc
说明:复制表(只复制结构,源表名:a 新表名:b)
--5、在销售明细表中按产品编号进行汇总,统计每种产品的销售数量和金额 select prod_id,sum(qty) totqty,sum(qty*unit_price) totprice from sale_item group by prod_id
--6、使用convert函数按客户编号统计每个客户1996年的订单总金额 select cust_id,sum(tot_amt) totprice from sales where convert(char(4),order_date,120)=’1996’ group by cust_id
2、查找与喻自强在同一个单位的员工姓名、性别、部门和职称 select emp_no,emp_name,dept,title from employee where emp_name<>’喻自强’ and dept in (select dept from employee where emp_name=’喻自强’)
-1、查找员工的编号、姓名、部门和出生日期,如果出生日期为空值, --显示日期不详,并按部门排序输出,日期格式为yyyy-mm-dd。 select emp_no ,emp_name ,dept , isnull(convert(char(10),birthday,120),’日期不详’) birthday from employee order by dept --

SQL语句 大全

SQL语句 大全

一、基础1、说明:创建数据库CREATE DATABASE database-name2、说明:删除数据库drop database dbname3、说明:备份sql server--- 创建备份数据的 deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack','c:\mssql7backup\MyNwind_1.dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2… from tab_old definition only5、说明:删除新表drop table tabname6、说明:增加一个列Alter table tabname add column col type注:列增加后将不能删除。

DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。

7、说明:添加主键:Alter table tabname add primary key(col) 说明:删除主键: Alter table tabname drop primary key(col) 8、说明:创建索引:create [unique] index idxname ontabname(col….)删除索引:drop index idxname注:索引是不可更改的,想更改必须删除重新建。

9、说明:创建视图:create view viewname as select statement删除视图:drop view viewname10、说明:几个简单的基本的sql语句选择:select * from table1 where 范围插入:insert into table1(field1,field2) values(value1,value2) 删除:delete from table1 where 范围更新:update table1 set field1=value1 where 范围查找:select * from table1 where field1 like ’%value1%’ ---like 的语法很精妙,查资料!排序:select * from table1 order by field1,field2 [desc]总数:select count as totalcount from table1求和:select sum(field1) as sumvalue from table1 平均:select avg(field1) as avgvalue from table1最大:select max(field1) as maxvalue from table1最小:select min(field1) as minvalue from table111、说明:几个高级查询运算词A:UNION 运算符UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。

语录 经典SQL语句

语录 经典SQL语句

语录大全经典SQL语句大全1(仅用于SQlServer)法二:select top 0 * into b from a2、说明:拷贝表(拷贝数据,源表名:a目标表名:b) (Access可用)insert into b(a, b, c) select d,e,f from b;3、说明:跨数据库之间表的拷贝(详细数据使用肯定路径) (Access 可用)insert into b(a, b, c) select d,e,f from b in ‘详细数据库’ where条件例子:..from b in " where..4、说明:子查询(表名1:a表名2:b)select a,b,c from a where a IN (select d from b )或者: select a,b,c from a where a IN (1,2,3)5、说明:显示文章、提交人和最终回复时间selecta.title,ername,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b6、说明:外连接查询(表名1:a表名2:b)select a.a, a.b, a.c, b.c,b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c7、说明:在线视图查询(表名1:a )select * from (SELECT a,b,c FROMa) T where t.a > 1;8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括select * from table1 where time between time1 and time2select a,b,c, from table1 where a not between数值1 and 数值29、说明:in的使用方法select * from tabl e1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)10、说明:两张关联表,删除主表中已经在副表中没有的信息delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )11、说明:四表联查问题:select * from a left inner join b ona.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where.....12、说明:日程支配提前五分钟提示SQL: select * from日程支配where datediff(minute,f开头时间,getdate())>513、说明:一条sql语句搞定数据库分页select top 10 b.* from (select top 20主键字段,排序字段from表名order by排序字段desc) a,表名b where b.主键字段= a.主键字段order by a.排序字段详细实现:关于数据库分页:declare @start int,@end int@sqlnvarchar(600)set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’exec sp_executesql @sql留意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特别的处理。

sql经典语句(SQLclassicsentences)

sql经典语句(SQLclassicsentences)

sql经典语句(SQL classic sentences)I. Basic operation1) DESC, the describe role is to display the structure of the data table using the form: desc data table name2) distinct eliminates duplicate data usage: select, distinct, field name, from data table3) order by field 1 ASC, field 2 desc4) nested queries select, emp.empno, emp.ename, emp.job, emp.salFrom scott.empWhere sal>= (select, Sal, from, scott.emp, where, ename='WARD');5) nested queries select, emp.empno, emp.ename, emp.job, in, emp.salFrom scott.empWhere, Sal, in (select, Sal, from, scott.emp, where, ename ='WARD');6) nested queries select, emp.empno, emp.ename, emp.job, any, emp.salFrom scott.empWhere Sal > any (select, Sal, from, scott.emp, where, job='MANAGER');Equivalent to (1) select, Sal, from, scott.emp, where, job ='MANAGER'(2) select, emp.empno, emp.ename, emp.job, emp.salFrom scott.empData found in where Sal > (1) data a, or, Sal > (1), data found in B, or, Sal > (1), CEg:Select, Sal, from, scott.emp, where, job ='MANAGER'results; 12,10,13Equivalent to sal=12,10,13 or SAL> (12, OR, 10, OR, 13)7) the intersection operation is the intersection concept in the set. The sum of the elements that belong to the set A and belongs to the set B is the intersection. In the command edit area, execute the following statement.Eg:(select, djbh, from, ck_rwd_hz) intersect (select, djbh, from, ck_rwd_mx) documents numbered the sameSelect * from ck_rwd_mx a,((select, djbh, from, ck_rwd_hz) intersect (select, djbh, from, ck_rwd_mx)) BWhere a.djbh =b.djbhTwo function1) ceil takes the minimum integer ceil (N) greater than or equal to the value N; select, Mgr, mgr/100, ceil (mgr/100), from, scott.emp;2) floor takes the maximum integer floor (N) less than or equal to the value N; select, Mgr, mgr/100, floor (mgr/100), from, scott.emp;3) the remainder of mod m divisible by mod (m, n) n4) power, m, N, square, mod (m, n)5) round m four, five, keep the n bit mod (m, n)Select round (8.655,2) from dual; 8.66Select round (8.653,2) from dual; 8.656) sign n>0, take 1; n=0, take 0; n<0, take -1;7) AVG averages AVG (field name)8) count statistics total count (field name) select (*) from scott.emp; select count (distinct job) from scott.emp;9) min calculates numeric fields minimum, select, min (SAL), minimum salary from scott.emp;10) max calculates numeric field maximum, select, max (SAL), highest salary from scott.emp;11) sum calculates the sum of numeric fields, select, sum (SAL), the sum of salaries, from, scott.emp;Three input data1) single data entryInsert into data tables (fields 1, fields 2,...) valuse (field name 1 values, field name 2 values,...)Numeric fields can write values directly; character fields add single quotation marks; date fields add single quotes; at the same time pay attention to the order of days and months2) multi line data entryInsert into data table (field name 1, field name 2,...)(select (field name 1 or operation, field name 2 or operation,...) from data table where condition)3) data replication between tablesCreate table scott.testAs(Select, distinct, empno, ename, hiredate, from, scott.emp, where, empno>=7000);Create table spkpk_liu as select * from spkfk; creates tables and copies data, but creates incomplete table informationThis is all the way to full table backups.Usually after the table is built, you need to see if you want to build the index and primary key again.And "create, table, spkpk_liu, as, select * from, spkfk.""After this table is built, many of the parameter values of the table are the default minimum values, such as the initial value of the original table 10M, and the new table is probably only 256K.Formal environment used in the table, generally do not recommend such a table built.In this way, just a little lazy, if you do so,A statement can achieve the purpose of building tables and inserting data.For example, you need to modify the data in table A, and you might want to back up the data from the A table before you modify it.This time you can use create table... As...This makes it easy to retrieve data from the A table in the futureYou can do this when you debug your own program, but you can't create processes, packages, functions like thisFour delete dataDelete deletes data; truncate deletes the entire table data, but retains the structure1) delete recordsDelete from scott.test where empno and empno <=8000 > = 7500;2) delete the entire dataTruncate table scott.test;Similarities and differences between truncate, delete and dropNote: the delete here refers to the delete statement without the where clauseThe same thing: truncate and the delete without the where clause, and drop will delete the data in the tableDifference:1. truncate and delete only delete data and do not delete the structure of the table (definition)The drop statement will delete the structure of the table, the dependent constraints (constrain), the trigger, and the index (index); the stored procedure / function that depends on the table will be retained, but the invalid state will be changedThe 2.delete statement is DML, which is put into the rollback segement before the transaction is committed, and if you have the corresponding trigger, the execution will be triggeredTruncate, drop is DDL, the operation takes effect immediately, and the original data is not put into the rollback segment and cannot be rolled back. The operation does not trigger trigger.. Obviously, the drop statement releases all the space occupied by the table3. speed, in general: drop>, truncate > deleteOn use, you want to delete part of the data rows, with delete,take care to bring the where clause. The rollback section is large enough to be rolled back through the ROBACK, and there is considerable room for recoveryTo delete tables, of course, use dropYou want to keep the table and delete all the data. If you have nothing to do with the transaction, you can use truncate. Truncate, table, XX, delete the entire table of data, there is no room for recovery, the benefits can be arranged in the table debris, release spaceSo it's better to back up the data firstIf you are tidying up the inner fragments of a table, you can use truncate to catch up with reuse stroage and then import / insert data againFive update dataUpdate data sheetSet field name, 1=, new assignment, field name, 2=, new assignment,...Where conditionUpdate scott.empSet, empno=8888, ename='TOM', hiredate='03-9, -2002'Where empno = 7566;Update scott.empSet sal=(select, sal+300, from, scott.emp, where, empno = 8099)Where empno=8099;Decode (condition, value 1, translation value 1, value 2, translation value 2, value n, translation value n, default value)Six data export1 export the database TEST completely, export the user name system password manager to D:\daochu.dmpExpsystem/manager@TESTfile=d:\daochu.dmp full=y2 export the system user in the database to the table of the sys userExpsystem/manager@TESTfile=d:\daochu.dmp only wner= (system, Sys)3 export tables table1 and table2 from the databaseExpsystem/manager@TESTfile=d:\daochu.dmp tables= (table1, table2)4 export the field filed1 in the table table1 in the database to data that starts with "00"Expsystem/manager@TESTfile=d:\daochu.dmp tables= (table1) query=\ "where filed1 like'00%'\""Explmis_wh/lmis@lmisbuffer=10000 only WNER=lmis_wh rows=nfile=d:\lmis_wh_nodata.dmp log=d:\lmis_wh_nodata.logImplmis/lmis@lmisbuffer=10000, fromuser=lmis_wh, touser=lmis, file=d:\lmis_wh_nodata.dmp, log=d:\lmis_wh_nodata.logC:\>implmis/lmis@lmisbuffer=50000000, full=n,file=e:\daochu.dmp, ignore=y, rows=yCommit=y compile=y fromuser=lmis_wh touser=lmisSeven data import1 import data from the D:\daochu.dmp into the TEST database.Impsystem/manager@TEST file=d:\daochu.dmpThere may be a problem with it because some tables already exist, and then it is reported wrong, and the table is not imported.It's OK to add ignore=y at the back.2 import table table1 from d:\daochu.dmpImpsystem/manager@TEST file=d:\daochu.dmp tables= (table1)SQL definition: SQL is a database oriented general data processing language specification, can complete the following functions: data extraction query, insert modify delete data generation, modify and delete database objects, database security, database integrity control and data protection.SQL classification:DDL - Data Definition Language (CREATE, ALTER, DROP, DECLARE)DML - Data Manipulation Language (SELECT, DELETE, UPDATE, INSERT)DCL - data control language (GRANT, REVOKE, COMMIT, ROLLBACK) DDL - database definition language: direct submission. CREATE: used to create database objects.DECLARE: in addition to creating temporary tables that are used only during the process, the DECLARE statements are very similar to the CREATE statements. The only object that can be declared is the table. And must be added to the user temporary tablespace.DROP: you can delete any object created with CREATE (database object) and DECLARE (table).ALTER: allows you to modify information about certain databaseobjects. Cannot modify index.Eight, the following is mainly based on object presentation of basic grammar1, database:Create database: CREATE, DATABASE, database-name, [USING, CODESET, codeset, TERRITORY, territory]Note: the code page problem.Delete database: drop, database, dbname2, table:Create new table:Create, table, tabname (col1, Type1, [not, null], [primary, key], col2, type2, [not, null],...)Create a new table based on the existing table:A:create, table, tab_new, like, tab_oldB:create, table, tab_new, as, select, col1, col2... From tab_old definition onlyModify table:Add a column:Alter, table, tabname, add, column, col, typeNote: column added will not be deleted. The DB2 column after the data type does not change, the only change is to increase the size of the varchar. Add primary key:Alter, table, tabname, add, primary, key (Col)Delete Primary key:Alter, table, tabname, drop, primary, key (Col)Delete table: drop, table, tabnameAlter table BMDOC_LIUFDrop constraint PK1_BMDOC cascade;3, table space:Create table spaces: create, tablespace, tbsname, PageSize, 4K, managed, by, database, using (file, file, size)Adding containers to tablespace: alter, tablespace, tablespace_name, add (file,'filename', size)Note: the operation is irreversible and will not be removed after adding the container. Therefore, when it is added, pay attention to it.Delete tablespace: drop, tablespace, tbsname4, index:Create indexes: create, [unique], index, idxname, on, tabname (col... ).Delete index: drop, index, idxnameNote: the index is not modifiable. If you want to change it, you must delete it.5 views:Create views: create, view, VIEWNAME, as, select, statementDelete view: drop view VIEWNAMENote: the only change to the view is the reference type column, which changes the range of columns. None of the other definitions can be modified. The view becomes invalid when the view is based on the base table drop.DML - the database manipulation language, which does not implicitly submit the current transaction and is committed to the setting of the visual environment.SELECT: querying data from tablesNote: the connection in the condition avoids Cartesian productDELETE: delete data from existing tablesUPDATE: update data for existing tablesINSERT: insert data into existing tablesNote: whether DELETE, UPDATE, and INSERT are submitted directly depends on the environment in which the statement is executed.Pay attention to the full transaction log when executing.2, DELETE: delete records from the tableSyntax format:DELETE, FROM, tablename, WHERE (conditions)3, INSERT: insert a record into the tableSyntax format:INSERT INTO tablename (col1, col2),... ) VALUES (value1, Value2),... );INSERT INTO tablename (col1, col2),... ) VALUES (value1, Value2),... ) (value1, value2,... ),......Insert does not wait for any program and does not cause locking4, UPDATE:Syntax format:UPDATE tabname SET (col1=values1, col2=values2),... (WHERE) (conditions);Note: update is slower and requires indexing on the corresponding column.Nine permissionsDCL - Data Control LanguageGRANT - Grant user permissionsREVOKE - revoke user rightsCOMMIT - commit transactions can permanently modify the databaseROLLBACK - rollback transactions, eliminating all changes made after the last COMMIT command, so that the contents of the database are restored to the state after the last COMMIT execution.1, GRANT: all or administrators assign access rights to other usersSyntax format:Grant [all privileges|privileges,... On tabname VIEWNAME to [public|user |,... .2 and REVOKE: cancel one of the user's access rightsSyntax format:Revoke [all privileges|privileges,... On tabname VIEWNAME from [public|user |,... .Note: any permissions of users of instance level cannot be canceled. They are not authorized by grant, but are permissions implemented by groups.3, COMMIT: permanently records changes made in the transaction to the database.Syntax format:Commit [work]4, ROLLBACK: will undo all changes made since the last submission.Syntax format:Rollback [work]Ten advanced SQL brief introductionFirst, the query between the use of computing wordsA:UNION operatorThe UNION operator derives a result table by combining two other result tables (such as TABLE1 and TABLE2) and eliminating any duplicate rows in the table.When ALL is used with UNION (that is, UNION ALL), the duplicate rows are not eliminated. In the two case, each row of the derived table does not come from TABLE1, or from TABLE2.B:EXCEPT operatorThe EXCEPT operator derives a result table by including all rows in TABLE1, but not in TABLE2, and eliminating all duplicate rows. When ALL is used with EXCEPT (EXCEPT ALL), the duplicate rows are not eliminated.C:INTERSECT operatorThe INTERSECT operator derives a result table by including only rows in TABLE1 and TABLE2 and eliminating all duplicate rows. When ALL is used with INTERSECT (INTERSECT ALL), the duplicate rows are not eliminated.Note: several query results lines using arithmetic words must be consistent.Appendix: introduction to commonly used functions1, type conversion function:Converted to a numeric type:Decimal, double, Integer, smallint, realHex (ARG): 16 hexadecimal representation converted into parameters.Converted to string type:Char, varcharDigits (ARG): returns the string representation of Arg, and Arg must be decimal.Converted to date or time:Date, time, timestamp2, time and date:Year, quarter, month, week, day, hour, minute, secondDayofyear (ARG): returns the daily value of Arg in the yearDayofweek (ARG): returns the daily value of Arg in the weekDays (ARG): the integer representation of the return date, the number of days from the 0001-01-01.Midnight_seconds (ARG): the number of seconds between midnight and arg.Monthname (ARG): returns the month name of arg.Dayname (ARG): the week that returns arg.3 string function:Length, lcase, ucase, ltrim, rtrimCoalesce (arg1, arg2)... ) returns the first non null parameter in the argument set.Concat (arg1, arg2): connect two strings, arg1 and arg2.Insert (arg1, POS, size, arg2): returns a arg1 that removes size characters from POS and inserts arg2 into that location.Left (Arg, length): returns the leftmost length string of arg.Locate (arg1, arg2, &lt, pos>): find the location of the first occurrence of arg1 in arg2, specify POS, and start looking for the location of the arg1 from the POS of arg2.Posstr (arg1, arg2): returns the position where arg2 first appeared in arg1.Repeat (arg1, num_times): returns the string arg1 repeated num_times times.Replace (arg1, arg2, ARG3): replace all arg2 in arg1 to arg3.Right (Arg, length): returns a string consisting of lengthbytes on the left of the arg.Space (ARG): returns a string containing Arg spaces.Substr (arg1, POS, &lt, length>): returns the length character at the start of the POS position in arg1, and returns the remaining characters if no length is specified.4. Mathematical function:Abs, count, Max, min, sumCeil (ARG): returns the smallest integer greater than or equal to arg.Floor (ARG): returns the smallest integer less than or equal to the parameter.Mod (arg1,Arg2) returns arg1 by the remainder of the arg2, with the same symbol as arg1.Rand (): returns a random number between 1 and 1.Power (arg1, arg2): returns the arg2 power of arg1.Round (arg1, arg2): four, five into the truncated processing, arg2 is the number of bits, if arg2 is negative, then the number of decimal points before four to five processing.Sigh (ARG): symbolic designator to return arg. -1,0,1 representation.Truncate (arg1, arg2): truncate arg1, arg2 is the number of digits, and if arg2 is negative, keep the arg2 bits before the arg1 decimal point.5, others:Nullif (arg1, arg2): returns if the 2 arguments are equal, otherwise the argument 1 is returned。

SQL语句大全

SQL语句大全

SQL语句参考,包含Access、MySQL以及SQL Server基础创建数据库CREATE DATABASE database-name删除数据库drop database dbname备份sql server1.创建备份数据的device2. USE master3.EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'4.开始备份5.BACKUP DATABASE pubs TO testBack创建新表create table tabname(col1 type1 [not null] [primary key],c ol2 type2 [not null],..)根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2… from tab_old d efinition only删除新表drop table tabname增加一个列Alter table tabname add column col type注:列增加后将不能删除。

DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。

添加主键Alter table tabname add primary key(col)删除主键Alter table tabname drop primary key(col)创建索引create [unique] index idxname on tabname(col….)删除索引drop index idxname注:索引是不可更改的,想更改必须删除重新建。

创建视图create view viewname as select statement删除视图drop view viewname几个简单的基本的sql语句选择:select * from table1 where 范围插入:insert into table1(field1,field2) values(value1,value 2)删除:delete from table1 where 范围更新:update table1 set field1=value1 where 范围查找:select * from table1 where field1 like ’%value1%’ ---l ike的语法很精妙,查资料!排序:select * from table1 order by field1,field2 [desc]总数:select count as totalcount from table1求和:select sum(field1) as sumvalue from table1平均:select avg(field1) as avgvalue from table1最大:select max(field1) as maxvalue from table1最小:select min(field1) as minvalue from table1几个高级查询运算词UNION 运算符UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。

经典SQLSERVER语句大全

经典SQLSERVER语句大全

1.一、基础2.1、说明:创建数据库3.CREATE DATABASE database-name4.2、说明:删除数据库5.drop database dbname6.7.3、说明:备份sql server8.--- 创建备份数据的deviceE master10.EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'11.--- 开始备份12.BACKUP DATABASE test TO testBack13.14.4、说明:创建新表15.create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)16.根据已有的表创建新表:17.A:create table tab_new like tab_old (使用旧表创建新表)18.B:create table tab_new as select col1,col2… from tab_old definition only19.5、说明:删除新表20.drop table tabname21.6、说明:增加一个列22.Alter table tabname add column col type23.注:列增加后将不能删除。

DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。

24.7、说明:添加主键:Alter table tabname add primary key(col)25.说明:删除主键:Alter table tabname drop primary key(col)26.8、说明:创建索引:create [unique] index idxname on tabn ame(col….)27.删除索引:drop index idxname28.注:索引是不可更改的,想更改必须删除重新建。

厉害的sql语句

厉害的sql语句

厉害的sql语句以下是一些常见的强大的SQL语句示例:
1. 查询表中的所有数据:
```
SELECT * FROM 表名;
```
2. 查询特定条件下的数据:
```
SELECT * FROM 表名 WHERE 条件;
```
3. 查询表中的数据并按照某一列进行排序:```
SELECT * FROM 表名 ORDER BY 列名;
```
4. 查询表中的数据并统计某一列的总和:```
SELECT SUM(列名) FROM 表名;
```
5. 查询表中的数据并进行分组统计:
```
SELECT 列名, COUNT(*) FROM 表名 GROUP BY 列名;
```
6. 查询表中的数据并进行连接查询:
```
SELECT 表1.列名, 表2.列名 FROM 表1 INNER JOIN 表2 ON 表1.列名 = 表2.列名;
```
7. 更新表中的数据:
```
UPDATE 表名 SET 列名 = 值 WHERE 条件;
```
8. 插入新数据到表中:
```
INSERT INTO 表名 (列1, 列2) VALUES (值1, 值2);
```
9. 删除表中的数据:
```
DELETE FROM 表名 WHERE 条件;
```
这些只是一些常见的SQL语句示例,SQL语言非常强大,可以进行
更复杂的查询和操作。

具体的语句根据具体的需求来编写。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

精妙SQL语句收集摘要:一、基础二、提升三、技巧正文:SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。

一、基础1、说明:创建数据库Create DATABASE database-name2、说明:删除数据库drop database dbname3、说明:备份sql server--- 创建备份数据的deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) 根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2... from tab_old definition only5、说明:删除新表drop table tabname6、说明:增加一个列Alter table tabname add column col type注:列增加后将不能删除。

DB2中列加上后数据类型也不能改变,唯一能改变的是增加var char类型的长度。

7、说明:添加主键:Alter table tabname add primary key(col)说明:删除主键:Alter table tabname drop primary key(col)8、说明:创建索引:create [unique] index idxname on tabname(col....)删除索引:drop index idxname注:索引是不可更改的,想更改必须删除重新建。

9、说明:创建视图:create view viewname as select statement删除视图:drop view viewname10、说明:几个简单的基本的sql语句选择:select * from table1 where 范围插入:insert into table1(field1,field2) values(value1,value2)删除:delete from table1 where 范围更新:update table1 set field1=value1 where 范围查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! 排序:select * from table1 order by field1,field2 [desc]总数:select count as totalcount from table1求和:select sum(field1) as sumvalue from table1平均:select avg(field1) as avgvalue from table1最大:select max(field1) as maxvalue from table1最小:select min(field1) as minvalue from table111、说明:几个高级查询运算词A:UNION 运算符UNION 运算符通过组合其他两个结果表(例如TABLE1 和TABLE2)并消去表中任何重复行而派生出一个结果表。

当ALL 随UNION 一起使用时(即UNION ALL),不消除重复行。

两种情况下,派生表的每一行不是来自TABLE1 就是来自TABLE2。

B:EXCEPT 运算符EXCEPT 运算符通过包括所有在TABLE1 中但不在TABLE2 中的行并消除所有重复行而派生出一个结果表。

当ALL 随EXCEPT 一起使用时(EXCEPT ALL),不消除重复行。

C:INTERSECT 运算符INTERSECT 运算符通过只包括TABLE1 和TABLE2 中都有的行并消除所有重复行而派生出一个结果表。

当ALL 随INTERSECT 一起使用时(INTERSECT ALL),不消除重复行。

注:使用运算词的几个查询结果行必须是一致的。

12、说明:使用外连接A、left outer join:左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。

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 B:right outer join:右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。

C:full outer join:全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。

二、提升1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)法一:select * into b from a where 1<>1法二:select top 0 * into b from a2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)insert into b(a, b, c) select d,e,f from b;3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where..4、说明:子查询(表名1:a 表名2:b)select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)5、说明:显示文章、提交人和最后回复时间select a.title,ername,b.adddate from table a,(select max(adddate) adddate fro m table where table.title=a.title) b6、说明:外连接查询(表名1:a 表名2:b)select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c7、说明:在线视图查询(表名1:a )select * from (Select a,b,c FROM a) T where t.a > 1;8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括select * from table1 where time between time1 and time2select a,b,c, from table1 where a not between 数值1 and 数值29、说明:in 的使用方法select * from table1 where a [not] in ('值1','值2','值4','值6')10、说明:两张关联表,删除主表中已经在副表中没有的信息delete from table1 where not exists ( select * from table2 where table1.field1=ta ble2.field1 )11、说明:四表联查问题:select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner joi n d on a.a=d.d where .....12、说明:日程安排提前五分钟提醒SQL: select * from 日程安排where datediff('minute',f开始时间,getdate())>513、说明:一条sql 语句搞定数据库分页select top 10 b.* from (select top 20 主键字段,排序字段from 表名order by 排序字段desc) a,表名 b where b.主键字段= a.主键字段order by a.排序字段14、说明:前10条记录select top 10 * form table1 where 范围15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)16、说明:包括所有在TableA 中但不在TableB和TableC 中的行并消除所有重复行而派生出一个结果表(select a from tableA ) except (select a from tableB) except (select a from tableC)17、说明:随机取出10条数据select top 10 * from tablename order by newid()18、说明:随机选择记录select newid()19、说明:删除重复记录Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)20、说明:列出数据库里所有的表名select name from sysobjects where type='U'21、说明:列出表里的所有的select name from syscolumns where id=object_id('TableName')22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。

相关文档
最新文档