0% found this document useful (0 votes)
26 views30 pages

Sqldev320a Week4-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views30 pages

Sqldev320a Week4-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Instructor:

SQL Server boB Taylor


Developme [email protected]
nt m
SQLDEV
320 A
Spring
2021 MCA, MCM, MCSM,
Week 4 MCSE, MCSD, MCT,
Data Scientist
REVIEW

TODAY •

RECAP WEEK 3
QUIZ 3 REVIEW
• ASSIGNMENT 3 REVIEW
• DREA’S QUESTION ABOUT MARGIN

SQL SCRIPT PROGRAMMING

DATA MANIPULATION LANGUAGE (DML)

VARIABLES

TEMPORARY TABLES
Tackling Q05
Get the average total value of an order by year, month
include the average number of lines and the average number of items per order

1. Visualize what the result looks like


Year Month Order Total Avg Order Items Avg Order Lines Avg

2. Visualize what’s the immediate data needed to solve this question


Year Month Order Total Order Items Order Lines Order Id Order
Date
3. Visualize the data needed to fulfill
2 Order Id Order Order Id Order Line Id Line Total Quantity
Date Ordered
Tackling Q06
-- Q06 Get the total sales, cost, margin and
margin percent per country
-- Define Margin = Sales Value - Cost Value
-- Define Margin% = (1 - Cost/Sales) * 100
-- Hint: Follow the relationships
SalesOrderheader >-- SalesTerritory >--
CountryRegion
CASE SUM(D.[LineTotal])
WHEN NULL THEN NULL
WHEN 0 THEN NULL
ELSE ((SUM(D.[LineTotal]) - SUM(D.[OrderQty]*P.
[StandardCost]))/SUM(D.[LineTotal])) * 100
END AS [Margin Pct]
Tackling Q07
Get the top 5 salespersons by margin per year
Show information as: Year, Employee ID, Employee Name (Last, First), Margin

1. Visualize what the result looks like


Sales Year Sales Person ID Employee Margin
2011 279 Reiter, TsviMichael $ 36,183.91
2011 276 Mitchell, LindaC $ 34,657.19
2011 283 Campbell, DavidR $ 26,199.49
2011 280 Ansman-Wolfe, PamelaO $ 17,186.99
2011 281 Ito, ShuK $ 11,564.69
2012 287 Alberts, AmyE $ 2,324.43
2012 280 Ansman-Wolfe, PamelaO $ (2,609.43)

2. Visualize what’s the immediate data needed to solve this


Sales Year Sales Person ID Employee Margin Sales Year Sales Person ID Employee Margin
question
2011 279 Reiter, TsviMichael $ 36,183.91 2012 287 Alberts, AmyE $ 2,324.43
2011
2011
2011
276
283
280
Mitchell, LindaC
Campbell, DavidR
Ansman-Wolfe, PamelaO
$
$
$
34,657.19
26,199.49
17,186.99
+ 2012
2012
2012
280
284
290
Ansman-Wolfe, PamelaO
Mensa-Annan, TeteA
Varkey Chudukatil, RanjitR
$ (2,609.43)
$(24,407.57)
$(46,556.63)
+…
2011 281 Ito, ShuK $ 11,564.69 2012 283 Campbell, DavidR $(50,071.41)

3. How can you provide


• Set operations hard coded solution
the data:
• Defining the output rows from an input 2
Tackling Q08
Get all 2012 customers that did not return in 2013

1. Graphically imagine the Customers


question

2. Use set operations to get the


answer

2012 2013
Tackling Q09
Get the percent of Total Sales change (quarter over quarter) for 2011, 2012, 2013,
2014
3. Understand “(Current Quarter – 1) = Previous Quarter”

4. How to fold 2013, Q1 into 2012, Q4 ?


• Sequencing quarters continually …
• 2011, Q1 = 1
• 2011, Q2 = 2

j oi n
-
• …
• 2012, Q1 = 5
e l f
S
• …
Tackling Q09
Get the percent of Total Sales change (quarter over quarter) for 2011, 2012, 2013,
2014
1. Visualize the results
Current Quarter Year Current Quarter Current Quarter Sales Previous Quarter Year Previous Quarter Previous Quarter Sales Performance Pct
2011 2 $ NULL NULL NULL NULL
962,716.74
2011 3 $ 5,042,490.58 2011 2 $ 523.77%
962,716.74
2011 4 $ 6,636,464.89 2011 3 $ 5,042,490.58 131.61%
2012 1 $ 8,421,802.43 2011 4 $ 6,636,464.89 126.90%
2012 2 $ 8,808,557.97 2012 1 $ 8,421,802.43 104.59%

2. Visualize what’s the immediate data needed to solve this


question
Current Quarter Year Current Quarter Current Quarter Sales
2011 2 $
962,716.74
2011 3 $ 5,042,490.58
2011 4 $ 6,636,464.89
2012 1 $ 8,421,802.43
2012 2 $ 8,808,557.97
SQL Script
Programming
Script programming implies that T-SQL
commands are sent to the server for
execution.

A script is a file with one or more batches


of commands.

Scripting A statement is the single unit of execution

• Statements are usually ended with semicolons ';'

A batch is a collection of statements

• Some T-SQL commands need to be sent as a single


batch to the server
Scripting
GO signals the end of a batch of
Transact-SQL statements to the SQL
Server utilities.

GO is not a Transact-SQL statement; it


is a command recognized by the
sqlcmd and osql utilities and SQL
Server Management Studio Code editor.

SQL Server Utilities Statements


Values outside tables: Variables
Using Variables in SQL statements

Defining Setting

Defining variables Setting Values to Variables


SET @<variable name><assignment operator>
DECLARE@<variable name>[AS]<sqldata <expression>
type>[= <value>] <assignment operator> =, +=, -=, *=, /=, &=, ^=, |
SELECT @<variable name> = <expression>[,
@<variable name> = …]
Any place where a scalar value appears

5
SQL Script
Programming

Definition: 8Managing the way a script gets


executed based on information from the user
or past operations
IF [ELSE] statement
IF <boolean-expression> (<single-
statement>|<block-statement>) ELSE
(<single-statement>|<block-statement>)

<block-statement> := BEGIN
<single-statement> [<single-statement> …]
END
Control of Flow
IF…ELSE… RETURN
BEGIN … END THROW
BREAK TRY … CATCH …
CONTINUE WAITFOR
GOTO label
WHILE
IF [ELSE] statement
Selecting which set of
Data needs to be
statements to
evaluated as a
execute based on
Boolean expression
data

If Boolean expression If the expression


evaluates as TRUE, evaluates as ‘FALSE’
the following statement or the statement or ‘block’
‘block’ is executed. after the ELSE statement is
executed
(if the ELSE statement
exists)
IF vs CASE
IF is used to select the next block of instructions to CASE is used to select a value, during the execution of
execute, in the batch. a SQL statement.

IF is part of the script language, but not part of the SQL CASE is part of a SQL statement.
language.
-- Translate colors in English to Spanish
-- Make sure table doesn't exist before creating it SELECT DISTINCT
IF OBJECT_ID('dbo.IfTest', 'U') IS NOT NULL [Color] [English],
BEGIN CASE
DROP TABLE [dbo].[IfTest] WHEN Color IS NULL THEN NULL
PRINT 'TABLE DROPPED' ELSE
END CASE Color
WHEN THEN
CREATE TABLE [dbo].[IfTest] 'Black' 'Negro'
( Col1 INT NOT NULL WHEN 'Blue' THEN 'Azul'
PRIMARY KEY WHEN THEN
) 'Grey'
WHEN 'Silver''Gris'
THEN 'Plata'
WHEN
WHEN'Red'
'White'THEN 'Rojo'

THEN 'Blanco' WHEN


'Yellow' THEN 'Amarillo'
ELSE 'Indefinido'
END
END [Español]
FROM [Production].[Product]
IIF operator
Returns one of two values, depending on whether the
Boolean expression evaluates to true or false in SQL
Server.

SELECT [SalesOrderID]
, SUM(IIF([LineTotal] - [OrderQty] * [StandardCost] <
0, [LineTotal] - [OrderQty] * [StandardCost], NULL )) AS
[Total Negative Margin]
, SUM([LineTotal] - [OrderQty] * [StandardCost]) AS [Total
Order Margin]
FROM [Sales].[SalesOrderDetail] AS D join …
CHOOSE operator
Returns the item at the specified index from a
list of values in SQL Server
SELECT JobTitle,
HireDate,
Choose(Month(HireDate), 'Winter', 'Winter', 'Spring',
'Spring', 'Spring', 'Summer', 'Summer', 'Summer', 'Autumn',
'Autumn', 'Autumn', 'Winter') AS Quarter_Hired
FROM HumanResources.Employee
WHERE Year(HireDate) > 2005
ORDER BY Year(HireDate);
WHILE statement
Repeats a set of statements zero or more time based on data
While Boolean expression evaluates as TRUE, the following statement or ‘block’ is
executed.
If the expression evaluates as ‘FALSE’ the execution continues on the statement after the
WHILE block

13
WHILE statement
WHILE <boolean-expression> (<single-statement>|<block-
statement>)

<block-statement> := BEGIN
<single-statement>
[<single-statement>
…]
END

13
IF etc…

DEMO
SQL Script Programming

Table
variables

Only exists in the batch


Memory bound
Small to medium volumes of data
Only Primary Key Index available
Do not participate in Transactions
Can be passed between Functions
Temporary
tables
Have the # symbol in front of the name
=> table is created in tempdb database
Table life span is the session
If name starts with single #, table is accessible to the
session only
Local temp table
If name starts with (double) ##, table is accessible to all
sessions!!
Global temp table
Disk bound
Any size of data
Same syntax as create table
Foreign keys are not honored; you get a warning saying
that foreign key request was ignored.
Table variables and temp
tables
DEMO
SQL Script Programming
Tying everything together…
“Find all terminal parts and pieces
required to build a ‘Road-650 Black, 52’
bike (Id: 770)”
We are going to look into the BillOfMaterials table
SQL Script Programming
Tying everything
together…
“Find all terminal parts and pieces
required to build a ‘Road-650 Black,
52’ bike (Id: 770)”
1, 2, 3, 4, 316, 318, 320, 321, 322, 323, 324, 325, 326, 327, 329, 331,
332,
350, 351, 352, 355, 356, 398, 399, 400, 402, 459, 461, 462, 477, 478,
482,
483, 484, 485, 486, 487, 490, 492, 497, 504, 505, 506, 510, 517, 523,
SQL Script Programming

N
1
ProductAssemblyID ComponentID

SQL Script
517 497
517 528
517 530
517 911
738 324
738 325

Programming
738 326
738 327
738 399
738 492
ProductAssemblyID ComponentID 738 532
738 533
770 517 738 534
738 802
770 738 806 1
806 4
770 806 806 323
806 402
770 811 806 459
806 462
770 818 811 329
811 356
770 826 811 398
811 529
770 894 818 400
818 490
770 907 818 506
818 510
770 938 818 527
818 922
770 945 818 931
826 400
770 948 826 490
826 506
770 950 826 510
826 527
770 952 826 922
826 931
770 994 894
894
355
535
894 679
945 351
945 352
950 318
950 320
950 321
950 322
950 332
994 3
994 525
Week 4 Assignment

QUIZ 4 CODING ASSIGNMENT


Q10 IS A STRETCH GOAL

You might also like