Sie sind auf Seite 1von 16

Like in SQL Server

character string matches a specified pattern. A pattern can include regular characters and wildcard characters.

Select * from Person.Address where City like '[A-C]%'


Wildcard character
% _ (underscore) []

Description
Any string of zero or more characters. Any single character. Any single character within the specified range ([a-f]) or set ([abcdef]).

Enclosing characters in [ ] symbols indicates any single character within the [ ] is OK. ([a-c] means a, b, and c are OK. [ab] indicates a or b are OK).
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

Symbol
LIKE '5[%]' LIKE '[_]n' LIKE '[a-cdf]' LIKE '[-acdf]' LIKE '[ [ ]' LIKE ']' LIKE 'abc[_]d%' LIKE 'abc[def]'

Meaning
5% _n a, b, c, d, or f -, a, c, d, or f [ ] abc_d and abc_de abcd, abce, and abcf

SELECT p.FirstName, p.LastName, ph.PhoneNumber FROM Person.PersonPhone AS ph INNER JOIN Person.Person AS p ON ph.BusinessEntityID = p.BusinessEntityID WHERE ph.PhoneNumber NOT LIKE '415%' AND p.FirstName = 'Gail' ORDER BY p.LastName; GO Where Clause that uses LIKE Operator where where where where where where VendorCity VendorCity VendorCity VendorCity VendorCity VendorCity Like 'SAN%' Like 'Compu_er%' Like 'DAMI[EO]N' Like 'N[A-J]' Like 'N[^K-Y]' Not Like '[1-9]%'

Gail Gail Gail

Alexander Butler Erickson

1 (11) 500 555-0120 1 (11) 500 555-0191 834-555-0132

Santa Computer,Computers Damieon,Damion Na to NJ but not NV or NY All but not NK to NY 02107 and 8816

ISNULL In SQL Server


Do not use ISNULL to find NULL values. Use IS NULL instead. Else u get error An expression of non-boolean type specified in a context where a condition is expected, near 'ISNULL'. MSDN SELECT Name, Weight FROM Production.Product WHERE Weight IS NULL; GO

ISNULL (check_expression , replacement_value )

Using ISNULL with AVG


SELECT AVG(ISNULL(Weight, 50)) FROM Production.Product; GO

It substitutes the value 50 for all NULL entries in the Weight column of the Product table.

Using ISNUL
SELECT Description, DiscountPct, MinQty, ISNULL(MaxQty, 0.00) AS 'Max Quantity' FROM Sales.SpecialOffer; GO

WROX
SELECT sc.AccountNumber, ISNULL(CAST((SELECT Min(OrderDate) FROM Sales.SalesOrderHeader soh WHERE soh.CustomerID = sc.CustomerID) AS varchar),'NEVER ORDERED') AS OrderDate FROM Sales.Customer sc; AW00000697 AW00000698 AW00011012 NULL NULL Sep 17 2003 12:00AM SELECT sc.AccountNumber, CAST((SELECT Min(OrderDate) FROM Sales.SalesOrderHeader soh WHERE soh.CustomerID = sc.CustomerID) AS varchar) AS OrderDate FROM Sales.Customer sc; AW00000697 AW00000698 AW00011012 AW00011013 NEVER ORDERED NEVER ORDERED Sep 17 2003 12:00AM Oct 15 2003 12:00AM

ISNULL(MyColumnName, 0) where MyColumnName IS NULL For all column 0 is returned.

ORDER BY in SQL Server


Order By that uses an Alias
SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY Address, VendorName

That uses an Expression


SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY VendorContactLName + VendorContactFName

That uses an Column Position


SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY 2, 1

Columns of type ntext, text, image, geography, geometry, and xml cannot be used in an ORDER BY clause. There is no limit to the number of columns in the ORDER BY clause; however, the total size of the columns specified in an ORDER BY clause cannot exceed 8,060 bytes.

Column names and aliases specified in the ORDER BY clause must be defined in the select list if the SELECT statement contains one of the following clauses or operators:

UNION operator EXCEPT operator INTERSECT operator SELECT DISTINCT

In a query that uses UNION, EXCEPT, or INTERSECT operators, ORDER BY is allowed only at the end of the statement.
SELECT BusinessEntityID, SalariedFlag FROM HumanResources.Employee ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC ,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END; GO

SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName FROM Sales.vSalesPerson WHERE TerritoryName IS NOT NULL ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName ELSE CountryRegionName END;

BETWEEN in SQL Server


SELECT e.FirstName, e.LastName, ep.Rate FROM HumanResources.vEmployee e JOIN HumanResources.EmployeePayHistory ep ON e.BusinessEntityID = ep.BusinessEntityID WHERE ep.Rate BETWEEN 27 AND 30 ORDER BY ep.Rate;

27 and 30 Will Be Included SELECT BusinessEntityID, RateChangeDate FROM HumanResources.EmployeePayHistory WHERE RateChangeDate BETWEEN '20011212' AND '20020105';

SELECT BusinessEntityID, RateChangeDate FROM HumanResources.EmployeePayHistory WHERE BusinessEntityID not between 167 and 234 167 and 234 Will not be Included

The query retrieves the expected rows because the date values in the query and the datetime values stored in the RateChangeDate column have been specified without the time part of the date. When the time part is unspecified, it defaults to 12:00 A.M. Note that a row that contains a time part that is after 12:00 A.M. on 2002-01-05 would not be returned by this query because it falls outside the range.

IN in SQL Server
Determines whether a specified value matches any value in a subquery or a list. Any null values returned by subquery or expression that are compared to test_expression using IN or NOT IN return UNKNOWN. Using null values in together with IN or NOT IN can produce unexpected results.
SELECT p.FirstName, p.LastName, e.JobTitle FROM Person.Person p JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID WHERE e.JobTitle = 'Design Engineer' OR e.JobTitle = 'Tool Designer' OR e.JobTitle = 'Marketing Assistant'; GO SELECT p.FirstName, p.LastName, e.JobTitle FROM Person.Person p JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID WHERE e.JobTitle IN ('Design Engineer', 'Tool Designer', 'Marketing Assistant');

NOT IN
SELECT p.FirstName, p.LastName FROM Person.Person AS p JOIN Sales.SalesPerson AS sp ON p.BusinessEntityID = sp.BusinessEntityID WHERE p.BusinessEntityID NOT IN (SELECT BusinessEntityID FROM Sales.SalesPerson WHERE SalesQuota > 250000); GO NOT IN(CA,NY,NC)

OR in SQL Server
Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses.
SELECT FirstName, LastName, Shift FROM HumanResources.vEmployeeDepartmentHistory WHERE Department = 'Quality Assurance' AND (Shift = 'Evening' OR Shift = 'Night');

Precendence Level 1) AND 2) OR 3) NOT

The following table shows the result of the OR operator. TRUE FALSE UNKNOWN TRUE TRUE TRUE TRUE FALSE TRUE FALSE UNKNOWN UNKNOWN TRUE UNKNOWN UNKNOWN

AND in SQL Server


IF 1 = 1 AND 2 = 2 BEGIN PRINT 'First Example is TRUE' END ELSE PRINT 'First Example is FALSE'; GO IF 1 = 1 AND 2 = 17 BEGIN PRINT 'Second Example is TRUE' END ELSE PRINT 'Second Example is FALSE' ; GO
First Example is TRUE Second Example is FALSE

The following chart shows the outcomes when you compare TRUE and FALSE values by using the AND operator. TRUE FALSE UNKNOWN TRUE TRUE FALSE UNKNOWN FALSE FALSE FALSE FALSE UNKNOWN UNKNOWN FALSE UNKNOWN

USE AP Go Select * from Invoices where NOT (InvoiceTotal>=500 or Not InvoiceDate<='2008-07-01')


InvoiceID VendorID InvoiceNumber InvoiceTotal 2 123 263253241 40.20 3 123 963253234 138.75 4 123 2-000-2993 144.70 InvoiceDate 2008-04-10 00:00:00 2008-04-13 00:00:00 2008-04-16 00:00:00

Select * from Invoices where (InvoiceTotal>=500 or Not InvoiceDate<='2008-07-01')


InvoiceID VendorID InvoiceNumber InvoiceDate InvoiceTotal 1 122 989319-457 2008-04-08 00:00:00 3813.33 9 121 97/488 2008-04-24 00:00:00 601.95 12 96 I77271-O01 2008-04-26 00:00:00 662.00 15 48 P02-88D77S7 2008-05-03 00:00:00 856.92

NOT in SQL Server


SELECT ProductID, Name, Color, StandardCost FROM Production.Product WHERE ProductNumber LIKE 'BK-%' AND Color = 'Silver' AND NOT StandardCost > 400; GO

AVG in SQL Server


Returns the average of the values in a group. Null values are ignored.

SELECT AVG(VacationHours)AS 'Average vacation hours', SUM(SickLeaveHours) AS 'Total sick leave hours' FROM HumanResources.Employee

Average vacation hours 25

Total sick leave hours 97

WHERE JobTitle LIKE 'Vice President%'; SELECT TerritoryID, AVG(Bonus)as 'Average bonus', SUM(SalesYTD) as 'YTD sales' FROM Sales.SalesPerson GROUP BY TerritoryID; GO

TerritoryID Average bonus YTD sales NULL 0.00 1533087.5999 1 4133.3333 5518998.6092 2 4100.00 4557045.0459

Same as MIN MAX SUM

COUNT in SQL Server


COUNT works like the COUNT_BIG function. The only difference between the two functions is their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.
COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group and returns the number of nonnull values.

COUNT(DISTINCT expression) evaluates expression for each row in a group and returns the number of unique, nonnull values. SELECT COUNT(DISTINCT JobTitle ) FROM HumanResources.Employee; GO (No column name) 67 SELECT COUNT(*), AVG(Bonus) FROM Sales.SalesPerson WHERE SalesQuota > 25000; GO (No column name) (No column name) 14 3472.1428 SELECT COUNT(*) FROM Sales.SalesPerson WHERE SalesQuota > 25000; GO

(No column name) 14


SELECT COUNT(DISTINCT VendorID) AS NumberOfVendors, COUNT(VendorID) AS NumberOfInvoices, AVG(InvoiceTotal) AS AverageInvoiceAmount, SUM(InvoiceTotal) AS TotalInvoiceAmount FROM Invoices WHERE InvoiceDate > '2008-01-01'

NumberOfVendors 34

NumberOfInvoices 114

AverageInvoiceAmount TotalInvoiceAmount 1879.7413 214290.51

GROUP BY in SQL Server


Groups a selected set of rows into a set of summary rows by the values of one or more columns. One row is returned for each group. Aggregate functions in the SELECT clause <select> list provide information about each group instead of individual rows.

A general GROUP BY clause includes GROUPING SETS, CUBE, ROLLUP, WITH CUBE, or WITH ROLLUP. A simple GROUP BY clause does not include GROUPING SETS, CUBE, ROLLUP, WITH CUBE, or WITH ROLLUP. GROUP BY (), grand total, is considered a simple GROUP BY.

The following statements are allowed:


SELECT SELECT SELECT SELECT ColumnA, ColumnB FROM T GROUP BY ColumnA, ColumnB; ColumnA + ColumnB FROM T GROUP BY ColumnA, ColumnB; ColumnA + ColumnB FROM T GROUP BY ColumnA + ColumnB; ColumnA + ColumnB + constant FROM T GROUP BY ColumnA, ColumnB;

The following statements are not allowed:


SELECT ColumnA, ColumnB FROM T GROUP BY ColumnA + ColumnB SELECT ColumnA + constant + ColumnB FROM T GROUP BY ColumnA + ColumnB;

The HAVING clause is used with the GROUP BY clause to filter groups in the result set. The GROUP BY clause does not order the result set. Use the ORDER BY clause to order the result set. If a grouping column contains null values, all null values are considered equal, and they are put into a single group. You cannot use GROUP BY with an alias to replace a column name in the AS clause unless the alias replaces a column name in a derived table in the FROM clause. Duplicate grouping sets in a GROUPING SETS list are not eliminated. Duplicate grouping sets can be generated by specifying a column expression more than one time or by listing a column expression also generated by a CUBE or ROLLUP in the GROUPING SETS list. Distinct aggregates, for example, AVG (DISTINCT column_name), COUNT (DISTINCT column_name), and SUM (DISTINCT column_name) are supported with ROLLUP, CUBE, and GROUPING SETS. ROLLUP, CUBE, and GROUPING SETS cannot be specified in an indexed view.

GROUP BY or HAVING cannot be used directly on columns of ntext, text, or image.


SELECT SalesOrderID, SUM(LineTotal) AS SubTotal FROM Sales.SalesOrderDetail AS sod GROUP BY SalesOrderID ORDER BY SalesOrderID; SELECT a.City, COUNT(bea.AddressID) AS EmployeeCount FROM Person.BusinessEntityAddress AS bea INNER JOIN Person.Address AS a ON bea.AddressID = a.AddressID GROUP BY a.City ORDER BY a.City; SELECT DATEPART(yyyy,OrderDate) AS N'Year' ,SUM(TotalDue) AS N'Total Order Amount' FROM Sales.SalesOrderHeader GROUP BY DATEPART(yyyy,OrderDate) ORDER BY DATEPART(yyyy,OrderDate); SELECT DATEPART(yyyy,OrderDate) AS N'Year' ,SUM(TotalDue) AS N'Total Order Amount' FROM Sales.SalesOrderHeader GROUP BY DATEPART(yyyy,OrderDate) HAVING DATEPART(yyyy,OrderDate) >= N'2003' ORDER BY DATEPART(yyyy,OrderDate); SELECT CustomerID, SalesPersonID, COUNT(*) FROM Sales.SalesOrderHeader WHERE CustomerID <= 11010 GROUP BY CustomerID, SalesPersonID ORDER BY CustomerID, SalesPersonID; USE AP SELECT VendorID, AVG(InvoiceTotal) AS AverageInvoiceAmount FROM Invoices GROUP BY VendorID HAVING AVG(InvoiceTotal) > 2000 ORDER BY AverageInvoiceAmount DESC

SalesOrderID 43659 43660 43661 City Abingdon Albany Alexandria

SubTotal 20565.620600 1294.252900 32726.478600 EmployeeCount 1 4 2

Year 2001 2002 2003 2004 Year 2003 2004

Total Order Amount 14327552.2263 39875505.095 54307615.0868 32196912.4165 Total Order Amount 54307615.0868 32196912.4165

CustomerID 11000 NULL 11001 NULL 11002 NULL VendorID 110 72 104 99 119

SalesPersonID (No column name) 3 3 3 AverageInvoiceAmount 23978.482 10963.655 7125.34 6940.25 4901.26

Group BY determines how selected rows are grouped HAVING Clause determines how rows are included in final results.

Having Aggregate Functions can be coded in HAVING Clause. Having Clause can refer to column included in select clause

Where Where Clause cant contain Aggregate Functions. Can refer to any Column in Base table

AFTER

Search conditions is applied before rows are grouped and aggregate are calculated.

? ? ? ? ? ? ? MURACH ? ? ? ? ?

ROLLUP in SQL Server


The ROLLUP operator is useful in generating reports that contain subtotals and totals. The ROLLUP operator generates a result set that is similar to the result sets generated by the CUBE operator.

Following are the specific differences between CUBE and ROLLUP:


CUBE generates a result set that shows aggregates for all combinations of values in the selected columns. ROLLUP generates a result set that shows aggregates for a hierarchy of values in the selected columns.
SELECT VendorState, VendorCity, COUNT(*) AS QtyVendors FROM Vendors WHERE VendorState IN ('IA', 'NJ') GROUP BY ROLLUP(VendorState, VendorCity) -- 2008 syntax ORDER BY VendorState DESC, VendorCity DESC

SELECT VendorID, COUNT(*) AS InvoiceCount, SUM(InvoiceTotal) AS InvoiceTotal FROM Invoices --GROUP BY VendorID WITH ROLLUP GROUP BY ROLLUP(VendorID)

VendorID 121 122 123

InvoiceCount 8 9 47

InvoiceTotal 6940.25 23177.96 4378.02

NULL

114

214290.51

VendorState NJ NJ NJ

VendorCity Washington Fairfield East Brunswick

QtyVendors 1 1 2

NJ
IA IA

NULL
Washington Fairfield

4
1 1

IA NULL

NULL NULL

2 6

The result set of a ROLLUP operation has functionality similar to that returned by a COMPUTE BY. However, ROLLUP has the following advantages:

ROLLUP returns a single result set while COMPUTE BY returns multiple result sets that increase the complexity of application code. ROLLUP can be used in a server cursor while COMPUTE BY cannot. The query optimizer can sometimes generate more efficient execution plans for ROLLUP than it can for COMPUTE BY.

Murach Rollup add one or more summary row to a result set that uses grouping and aggregates.

First Example: - Here group by a single column. Here Groupby is on VendorID and InvoiceCount and Total is calculated for each vendor. Second Example: - On two column. GroupBy state and city. Here addition to summary row at the end of result set, summary row are included for each state. If you are using Rollup,u cant use DISTINCT keyword in any of aggregate functions.

UNION in SQL Server


The following are basic rules for combining the result sets of two queries by using UNION:

The number and the order of the columns must be the same in all queries. The data types must be compatible. By default, Union excludes duplicate row, if you want to include duplicate rows use ALL keyword. Column name in final table is taken from first select clause. To sort the column in final result set, use ORDERBY after last select, this must refer to a name in first SELECT clause.
Source Paid Paid Paid Active InvoiceNumber P-0259 0-2060 40318 P-0608 InvoiceDate InvoiceTotal 26881.40 23517.58 21842.00 20551.18

USE Examples SELECT 'Active' AS Source, InvoiceNumber, InvoiceDate, InvoiceTotal FROM ActiveInvoices WHERE InvoiceDate >= '06/01/2008' UNION SELECT 'Paid' AS Source, InvoiceNumber, InvoiceDate, InvoiceTotal FROM PaidInvoices WHERE InvoiceDate >= '06/01/2008' ORDER BY InvoiceTotal DESC

2008-07-19 00:00:00 2008-07-24 00:00:00 2008-06-01 00:00:00 2008-07-23 00:00:00

UNION THAT USES DATA FROM SAME TABLE 1