สไลด์วิชา structured query language

40
Structured Query Language SQL

Upload: know2pro

Post on 27-Sep-2015

33 views

Category:

Documents


4 download

DESCRIPTION

สไลด์วิชา Structured Query Language

TRANSCRIPT

  • Structured Query LanguageSQL

  • Transact-SQL StatementsYou can group SQL statements into three categories: Data Definition Language (DDL) statements, which enable you to create database objects. Data Manipulation Language (DML) statements, which enable you to query or modify data. Data Control Language (DCL) statements, which enable you to determine, set, or revoke users permissions to SQL databases and their object

  • SELECTSELECT select_list ()[INTO new table] ( select new table)FROM table_source ( 1 )[WHERE search_condition] ( select)[GROUP BY group_by_expression] ()[HAVING search_condition] ()[ORDER BY order_expression [ASC|DESC]] ( order_exp)

  • select customerid, companyname, city, country from customersSelect * from customers() select customerid , companyname [], city as [], country from customersselect customerid, , companyname from customers

  • select orderid, productid, unitprice, quantity, quantity*unitprice as [total] from [order details] total ()

  • arithmetic operators + - * / %The arithmetic operators that perform addition, subtraction, division, and multiplication can be used on any numeric column or expression ( int, smallint, tinyint, decimal, numeric, float, real, money, or smallmoney). The modulo operator can only be used on int, smallint, or tinyint columns or expressions

  • Math. Function- Ceiling(), Floor(), The CEILING function returns the smallest integer greater than or equal to the given numeric expression. The FLOOR function returns the largest integer less than or equal to the given numeric expression. For example, given a numeric expression of 12.9273, CEILING returns 13, and FLOOR returns 12.

  • Math. Function - Round()Returns a numeric expression, rounded to the specified length or precision.SyntaxROUND ( numeric_expression , length [ , function ] ) Argumentsnumeric_expression Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

  • Math. Function - Round()lengthIs the precision to which numeric_expression is to be rounded. length must be tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal places specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.functionIs the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

  • String function : strReturns character data converted from numeric data.SyntaxSTR ( float_expression [ , length [ , decimal ] ] ) Argumentsfloat_expressionIs an expression of approximate numeric (float) data type with a decimal point. Do not use a function or subquery as the float_expression in the STR function. lengthIs the total length, including decimal point, sign, digits, and spaces. The default is 10.decimalIs the number of places to the right of the decimal point

  • String function : Len()Left()/Right()LTrim()/RTrim()SubString()Lower()/Upper()

  • Date function:GetDate() // Default datetime DatePart()DateName()Day() / Month() / Year()DateAdd()DateDiff()

  • exercise SQL select *,quantity*unitprice as total from "order details 1) total () 1) total () 1) total () ()

  • Filtering Rows with WHERE and HAVING The WHERE and HAVING clauses in a SELECT statement control the rows from the source tables that are used to build the result set. WHERE and HAVING are filters. They specify a series of search conditions, and only those rows that meet the terms of the search conditions are used to build the result set The HAVING clause is typically used in conjunction with the GROUP BY clause, although it can be specified without GROUP BY. The HAVING clause specifies further filters that are applied after the WHERE clause filters Ex. SELECT CustomerID, CompanyName FROM Customers WHERE Region = 'WA'

  • search conditionsComparison Search Conditions >, =, , !< ; WHERE [not] Col > Range Search Conditions WHERE Col [not] Between and List Search Conditions WHERE Col [not] in (,,)Pattern Matching in Search Conditions WHERE Col [not] Like ( Wildcard % _ [] [^])NULL Comparison Search Conditions WHERE Col is [not] null

    (Col = column expression)

  • select productname, unitprice, unitsinstock from products where unitsinstock >=100select productname,unitprice,unitsinstock from products where unitsinstock between 100 and 200

  • select customerid,city,country from customers where country = 'usa' or country = 'uk -- where country in('usa,'uk)Select customerid,companyname from customers where companyname like %De% --where companyname like _[^aeiou]%select customerid,region from customers where region is not null

  • Aggregate FunctionAggregate functions (such as SUM, AVG, COUNT, MAX, and MIN) generate summary values in query result sets. An aggregate function (with the exception of COUNT(*)) processes all the selected values in a single column to produce a single result value. Aggregate functions can be applied to all rows in a table, to a subset of the table specified by a WHERE clause, or to one or more groups of rows in the table.

  • select sum(unitprice)/ count(unitprice) as "AVG1", avg(unitprice) as "AVG2" from productsselect count(*) from customers where country ='usaselect sum(unitprice*quantity) from order details where orderid ='10248'

  • GROUP BY clauseThe GROUP BY clause is used to produce aggregate values for each row in the result set. When used without a GROUP BY clause, aggregate functions report only one aggregate value for a SELECT statement.The GROUP BY keywords are followed by a list of columns, known as the grouping columns. The GROUP BY clause restricts the rows of the result set; there is only one row for each distinct value in the grouping column or columns. Each result set row contains summary data related to the specific value in its grouping columns.

  • select orderid,sum(unitprice*quantity) from "order details"group by orderidselect country,city,count(*) from customers group by country,city [order by 1,2]select country,city,count(*)as test from customers where city like 'C% group by country,city having country = 'uk' order by 1,2

  • 1996

  • Exercise SQL . . order order , order () order 20

  • ORDER BY [ASC|DESC] Select ASC[ending] [DESCending] Select From [where] [group by] [having ] [order by [asc|desc]

  • (TOP N [PERCENT]) DISTINCT COMPUTE Aggregate Function 1 () ex. Compute Sum(quantity)COMPUTE BY Aggregate Function ex. Compute Sum(quantity) by ColA, ColB, ColA, ColB,

  • INSERTINSERT [INTO] [(,...)] VALUES ( | | NULL | DEFAULT,...)

  • Ex.-- insert all column Insert std values('004','BBB,null)

    -- insert some column Insert std(std_id,std_name) values('004','BBB')

  • INSERT: excerciseSTD 001, AAA, null 002, CCC, null 003, CCC, nullSUBJECT C01, Cal 1, null C02, Cal 2, default C03, Cal 3, defaultREGIS 001,C01,null 001,C02,null 002,C01,null 002,C02,null

  • UPDATEUPDATE SET { = | | () | NULL | DEFAULT,...} [WHERE ]

  • Ex.Update std set std_name='BBB', tell='357222 where std_id='004

    Update customers set city = Bangkok where country=Thailand

  • Update : exercise cal 1 comp prog . 2 BBB

  • DELETEDELETE [FROM] WHERE

    Ex. delete std where std_id ='001 delete customers where country in (uk,usa)

  • Inner join (including self join)Outer join (Left, Right, Full)Cross join

  • Inner join 2 2 match select companyname, orderid, orderdate from customers c inner join orders o on c.cust_id = o.cust_id

  • Outer join (Left join, Right join) 2 ()select cust_name, o.order_num, order_date from customers c left|right|full join orders o on c.cust_id = o.cust_id

  • Cross join Cartesian Product select cust_name, o.order_num, order_date from customers c cross join orders o Relational Database

  • Exercise: . . . (Left join Right join) . . . .

  • Where (Sql server Syntax)Select cust_name,o.order_num,order_date from customers c , orders o where c.cust_id = o.cust_idselect cust_name,o.order_num,order_date from customers c , orders o where c.cust_id *= o.cust_idselect cust_name,o.order_num,order_date from customers c , orders o where c.cust_id =* o.cust_id

  • Join : exercise SQL Server syntax . . . (Left join Right join) . . . .

  • $$