SlideShare a Scribd company logo
CIS276DB
Module 6 Assignment
1. Write a select statement based on the InvoiceTotal column of
the Invoices table:
integer value.
Name it IntTotal. Name it IntTotal.
datatype decimal
with one digit to the right. Name it DecimalTotal.
datatype that
outputs 2 digits to the right of the decimal point and all
comma’s to the
left (i.e. 3, 106.34). Name it FormatTotal.
2. Write a select statement that returns 4 columns based on the
Vendors table:
- Name): this column should be formatted in
the following
way; VendorContactFName followed by the last initial and a
period
(example: “John S.”).
- StateInitial): the VendorState first initial in
lowercase.
- Phone): VendorPhone without the area code
- TodaysDate): the current date formatted like-
Apr 18,
2008
Filter the results to only return rows where the VendorPhone
prefix is equal to
‘(800)’. Sort the results by VendorState and LastName.
3. Business Case: The current date is 12/1/2008; the accounting
department
would like to know which invoices with a balance due are still
outstanding and
the current age in days their invoice is beyond the invoice date.
Write a select statement that returns 4 columns: VendorName,
InvoiceTotal,
InvoiceDate and InvoiceAge (use the appropriate function that
will return the
number of days between the InvoiceDate and ‘12/1/2008’).
Filter the results to only return rows where there is a balance
due and the
InvoiceAge is greater than 132. Sort the results by
VendorName.
4. Write a select statement that returns 7 columns:
- WrittenDate): use the function that will
convert
InvoiceDate to this format; Apr 18, 2008
- NewDate): use the function that will add 45
days to
InvoiceDate and convert it to this format; Apr 18, 2008
- DayOfWeek): Use the function that will
return the name
of the day of NewDate (i.e. Saturday)
- MonthPart): Use the function that will return
the name
of the month of NewDate (i.e March)
- DatePart): Use the function that will return
the day date
of NewDate (i.e. 18 {of Apr 18, 2008})
- YearPart): Use the function that will return
the year from
NewDate (i.e. 2008)
Sort the results by InvoiceDate.
5. Business Case: The executive committee is implementing a
purchase discount
program based on the invoice total for a vendor. As such, they
need to gauge how
many invoices might qualify for a discount. Invoices that are
below $100 will NOT
qualify for a discount. Invoices between 101 and $500 are a low
consideration,
invoices between 501 and $1000 are a higher consideration and
invoices above
$1000 are the highest consideration.
Write a select statement that returns 4 columns: VendorName,
InvoiceNumber,
InvoiceTotal, and PotentialDiscount.
PotentialDiscount is a column that will contain the result
expression from a
CASE statement that contains 4 conditionals based on the
InvoiceTotal column;
Conditionals Result expression
InvoiceTotal < 100 ‘No discount consideration’
InvoiceTotal 101-500 ‘Discount potential 3’
InvoiceTotal 501-1000 ‘Discount potential 2’
InvoiceTotal > 1000 ‘Discount potential 1’
Sort the results by InvoiceTotal.
6. Business Case: The accounting department would like to
know the current
balances for vendors that owe money on their accounts. They
would like to
categorize vendors who owe over $11,000 as having a Very
High debt level, those
who owe between $11,000 and over $500 as having a High debt
level, those who
owe between $500 and over $200 as having a Medium debt level
and anyone
else as a Low debt level.
Write a select statement that returns 3 columns:
function
o Sum of Balances greater than $11,000 = ‘Very High’
o Sum of Balances between $11,000 and greater than $500 =
‘High’
o Sum of Balances between $500 and greater than $200 =
‘Medium’
o Sum of Balances equal to $200 or less = ‘Low’
Filter the results to only include vendors where a balance is due
and sort the
results from the sum of largest balance to smallest.
To display a column where the data type cannot be implicitly
converted, use a CAST function
USE AP;
SELECT InvoiceTotal, InvoiceDate, CAST(InvoiceTotal AS
varchar) AS ITVc,
CAST(InvoiceDate AS money) AS TimeIsMoney
FROM Invoices
CONVERT allows you to format certain datatypes (dates
primarily)
SELECT CONVERT(varchar, InvoiceDate) AS S1,
CONVERT(varchar, InvoiceDate,1) AS S2,
CONVERT(varchar, InvoiceDate,109) AS S3,
CONVERT(varchar, InvoiceDate, 8) AS S4,
CONVERT(varchar, InvoiceDate, 10) AS S5,
CONVERT(varchar, InvoiceTotal, 1) AS M1,
CONVERT(varchar, InvoiceTotal, 101) AS M2,
CONVERT(varchar, InvoiceTotal, 53) AS M3
FROM Invoices
Using carriage returns and line feeds (CHAR(13), CHAR(10))
you can output columns as text (example here- address label)
USE AP
SELECT VendorContactFName + ' ' + VendorContactLName
+ CHAR(13) + CHAR(10)
+ VendorAddress1 + CHAR(13) + CHAR(10)
+ VendorCity + ', ' + VendorState + ' '
+ VendorZipCode
+ CHAR(13)
FROM Vendors
As it turns out, you don’t need the line feed!
USE AP
SELECT VendorContactFName + ' ' + VendorContactLName
+ CHAR(13)
+ VendorAddress1 + CHAR(13)
+ VendorCity + ', ' + VendorState + ' '
+ VendorZipCode
+ CHAR(13)
FROM Vendors
String functions
USE AP
SELECT VendorName, LEN(vendorName) AS L,
UPPER(VendorName) AS U, LOWER(VendorName) AS
Lw,
RIGHT(VendorName, 6) AS Rn,
LEFT(VendorName, 6) AS Ln
FROM Vendors
String functions
USE AP
SELECT VendorAddress1, CHARINDEX('po', VendorAddress1)
AS wiPO,
PATINDEX('%in%', VendorAddress1) AS wiIN,
REVERSE(VendorAddress1) AS scramble
FROM Vendors
String functions
USE AP
SELECT VendorPhone,
REPLACE(RIGHT(VendorPhone, 13), ') ', '-') AS
Noparenthesis,
SUBSTRING(VendorPhone, 7,8) AS NoAreaCode,
SUBSTRING(VendorPhone, 2,3) AS AreaCode
FROM Vendors
String functions
USE Examples
SELECT Name, LEFT(Name, CHARINDEX(' ', Name)-1) AS
FirstName,
RIGHT(Name, LEN(Name) - CHARINDEX(' ', Name)) AS
LastName
FROM StringSample
Date functions using only GETDATE()
SELECT GETDATE() AS TodaysDate, DAY(GETDATE()) AS
CurrDay,
MONTH(GETDATE()) AS CurrMonth,
YEAR(GETDATE()) AS CurrYear,
DATENAME(month, GETDATE()) AS MonthName
Date functions
USE AP
SELECT InvoiceDate, InvoiceDate + 14 AS IDpTW,
DATEDIFF(month, InvoiceDate, GETDATE()) AS
DateDif,
CONVERT(varchar, DATEADD(year, 9, InvoiceDate),107)
AS DateAdd
FROM Invoices
Ranking functions
USE AP
SELECT NTILE(4) OVER (ORDER BY InvoiceTotal DESC) AS
Rank,
InvoiceTotal, InvoiceNumber
FROM Invoices
Ranking functions
USE AP
SELECT NTILE(10) OVER (ORDER BY InvoiceTotal DESC)
AS Rank,
InvoiceTotal, InvoiceNumber
FROM Invoices
Ranking functions
USE AP
SELECT RANK() OVER (ORDER BY InvoiceTotal) AS Rank,
DENSE_RANK() OVER (ORDER BY InvoiceTotal) AS
DenseRank,
InvoiceTotal
FROM Invoices
Ranking functions
USE AP
SELECT ROW_NUMBER() OVER (PARTITION BY
VendorState, VendorCity ORDER BY VendorName)
AS RowNum, VendorName, VendorState, VendorCity
FROM Vendors
Case Function
USE AP
SELECT VendorName, InvoiceTotal,
CASE
WHEN InvoiceTotal > 5000 THEN 'We owe our
souls'
WHEN InvoiceTotal BETWEEN 1000 AND 5000
THEN 'Its ok'
WHEN InvoiceTotal BETWEEN 100 AND 999 THEN
'much better'
WHEN InvoiceTotal < 100 THEN 'awesome'
END AS DebtType
FROM Vendors v JOIN Invoices i
ON V.VendorID = i.VendorID
ORDER BY InvoiceTotal DESC
Case Function
USE AP
SELECT InvoiceNumber, TermsID,
CASE TermsID
WHEN 1 THEN 'Net due 10 days'
WHEN 2 THEN 'Net due 20 days'
WHEN 3 THEN 'Net due 30 days'
WHEN 4 THEN 'Net due 40 days'
WHEN 5 THEN 'Net due 50 days'
END AS Terms
FROM Invoices
ORDER BY Terms
Case Function using GROUPING (this removes the NULL value
that’s present in a summary query that uses a ROLLUP or
CUBE operator)
USE AP
SELECT
CASE
WHEN GROUPING(VendorState) = 1 THEN 'All'
ELSE VendorState
END AS VendorState,
CASE
WHEN GROUPING(VendorCity) = 1 THEN 'All'
ELSE VendorCity
END AS VendorCity,
COUNT(*) AS QtyVend
FROM Vendors
WHERE VendorState IN('IA', 'NJ')
GROUP BY VendorState, VendorCity WITH ROLLUP
ORDER BY VendorState DESC, VendorCity
COALESCE removes null values that are present in columns-
here using the left join between Vendors and Invoices- vendors
that don’t have an Invoice (therefore don’t have an
InvoiceTotal) will display NULL in the InvoiceTotal column.
Using COALESCE, we can substitute a value for NULL (since
InvoiceTotal is a money data type, we have to use a CAST
function to substitute a varchar data type- ‘No Invoice Total’).
USE AP
SELECT VendorName, COALESCE(CAST(InvoiceTotal AS
Varchar), 'No Invoice Total')
AS InvoiceTotal
FROM Vendors v LEFT JOIN Invoices i
ON v.Vendorid = i.VendorID
ORDER BY VendorName
ISNULL works the same as COALESCE
USE AP
SELECT VendorName, ISNULL(CAST(InvoiceTotal AS
Varchar), 'No Invoice Total')
AS InvoiceTotal
FROM Vendors v LEFT JOIN Invoices i
ON v.Vendorid = i.VendorID
ORDER BY VendorName
For this ISNULL example, we substitute in a money value
(0.00) so CAST isn’t necessary
USE AP
SELECT VendorName, ISNULL(InvoiceTotal, 0.00)
AS InvoiceTotal
FROM Vendors v LEFT JOIN Invoices i
ON v.Vendorid = i.VendorID
ORDER BY VendorName
IIF Function
USE AP
SELECT InvoiceTotal, VendorState,
IIF(InvoiceTotal>1500, 'High', 'Low') AS InvoiceValue,
IIF(VendorState = 'CA', 'Cali Vendor', 'Not Cali') AS
StateVendor
FROM Vendors v JOIN Invoices i
ON v.VendorID = i.vendorID
Creating test tables for adding, modifying and deleting data
USE AP
SELECT *
INTO Invoice1
FROM Invoices
Creating test tables for adding, modifying and deleting data
USE AP
SELECT *
INTO Vendor1
FROM Vendors
Creating test tables for adding, modifying and deleting data
(partial table)
USE AP
SELECT *
INTO Invoice2
FROM Invoices
WHERE InvoiceTotal-PaymentTotal-CreditTotal = 0
INSERT statement that only uses a VALUE list
USE AP
INSERT INTO Invoice2
VALUES(1, '123456', '1/1/2016', 100.00, 0, 0, 1, '1/10/2016',
NULL)
INSERT statement that uses a COLUMN list along with several
VALUE lists
USE AP
INSERT INTO Invoice2
(InvoiceNumber, VendorID, InvoiceDate,
InvoiceTotal,PaymentTotal,
CreditTotal, InvoiceDueDate, TermsID)
VALUES('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1),
('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1),
('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1),
('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1),
('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1)
INSERT statement that uses a subquery
USE AP
INSERT INTO Invoice1
(VendorID, InvoiceTotal, InvoiceNumber, CreditTotal,
TermsID,
PaymentTotal, InvoiceDate, InvoiceDueDate)
SELECT VendorID, InvoiceTotal, InvoiceNumber, CreditTotal,
TermsID,
PaymentTotal, InvoiceDate, InvoiceDueDate
FROM Invoices
WHERE InvoiceTotal > 100
UPDATE statement (UPDATES REQUIRE A WHERE!)
USE AP
UPDATE Invoice2
SET PaymentDate = '1/14/2016',
PaymentTotal = PaymentTotal + 100
WHERE InvoiceNumber = '123456'
UPDATE statement (UPDATES REQUIRE A WHERE!)
USE AP
UPDATE Invoice1
SET CreditTotal = CreditTotal + 4.50
WHERE VendorID =
(SELECT VendorID
FROM Vendor1
WHERE VendorName = 'Blue Cross')
DELETE statement (DELETES REQUIRE A WHERE!)
USE AP
DELETE Invoice1
WHERE InvoiceID = 4
DROP Table syntax (forgot to do this in class
DROP TABLE Invoice1
DROP TABLE Invoice2
DROP TABLE vendor1
Databases/AP.mdf
Databases/AP_AllObjects.mdf
Databases/AP_AllObjects_log.LDF
Databases/AP_log.LDF
Databases/Examples.mdf
Databases/Examples_log.LDF
Databases/ProductOrders.mdf
Databases/ProductOrders_log.LDF
Databases/Test_AP.mdf
Databases/Test_AP_log.LDF

More Related Content

Similar to CIS276DB Module 6 Assignment 1. Write a select sta.docx

Chapter 8 the six column work sheet
Chapter 8 the six column work sheetChapter 8 the six column work sheet
Chapter 8 the six column work sheet
Iva Walton
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
anthonyfeliciano
 
As with all projects in this course, your program’s output wil.docx
As with all projects in this course, your program’s output wil.docxAs with all projects in this course, your program’s output wil.docx
As with all projects in this course, your program’s output wil.docx
randymartin91030
 
Cover PageComplete and copy the following to Word for your cover p.docx
Cover PageComplete and copy the following to Word for your cover p.docxCover PageComplete and copy the following to Word for your cover p.docx
Cover PageComplete and copy the following to Word for your cover p.docx
faithxdunce63732
 
LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific_financialmodelling_excelshortcuts1LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific Corporate Finance
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
Achmad Solichin
 
Les03
Les03Les03
Crosstab query techniques
Crosstab query techniquesCrosstab query techniques
Crosstab query techniques
aabaap
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
Charles Givre
 
Marcus Matthews
Marcus MatthewsMarcus Matthews
Marcus Matthews
MarcusMatthews38
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
Huda Alameen
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
dmcglasson
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
guest0ff0f54d
 
Oracle APPS :Receivables Auto Invoice
Oracle APPS :Receivables Auto InvoiceOracle APPS :Receivables Auto Invoice
Oracle APPS :Receivables Auto Invoice
Sekhar Byna
 
List of Coversions in Oracle Apps
List of Coversions in Oracle AppsList of Coversions in Oracle Apps
List of Coversions in Oracle Apps
Prem Kumar
 
Interface
InterfaceInterface
F 04 gl account clearing
F 04 gl account clearingF 04 gl account clearing
F 04 gl account clearing
Farooq Wangde
 
460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt
460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt
460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt
sporto2013
 
SQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptxSQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptx
Select Distinct Limited
 

Similar to CIS276DB Module 6 Assignment 1. Write a select sta.docx (19)

Chapter 8 the six column work sheet
Chapter 8 the six column work sheetChapter 8 the six column work sheet
Chapter 8 the six column work sheet
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
 
As with all projects in this course, your program’s output wil.docx
As with all projects in this course, your program’s output wil.docxAs with all projects in this course, your program’s output wil.docx
As with all projects in this course, your program’s output wil.docx
 
Cover PageComplete and copy the following to Word for your cover p.docx
Cover PageComplete and copy the following to Word for your cover p.docxCover PageComplete and copy the following to Word for your cover p.docx
Cover PageComplete and copy the following to Word for your cover p.docx
 
LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific_financialmodelling_excelshortcuts1LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific_financialmodelling_excelshortcuts1
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 
Les03
Les03Les03
Les03
 
Crosstab query techniques
Crosstab query techniquesCrosstab query techniques
Crosstab query techniques
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
 
Marcus Matthews
Marcus MatthewsMarcus Matthews
Marcus Matthews
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
Oracle APPS :Receivables Auto Invoice
Oracle APPS :Receivables Auto InvoiceOracle APPS :Receivables Auto Invoice
Oracle APPS :Receivables Auto Invoice
 
List of Coversions in Oracle Apps
List of Coversions in Oracle AppsList of Coversions in Oracle Apps
List of Coversions in Oracle Apps
 
Interface
InterfaceInterface
Interface
 
F 04 gl account clearing
F 04 gl account clearingF 04 gl account clearing
F 04 gl account clearing
 
460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt
460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt
460970787-93626369-Oracle-Accounts-Receivables-1-ppt.ppt
 
SQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptxSQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptx
 

More from clarebernice

Consider the vision for a successful Southwest Transit marketing tea.docx
Consider the vision for a successful Southwest Transit marketing tea.docxConsider the vision for a successful Southwest Transit marketing tea.docx
Consider the vision for a successful Southwest Transit marketing tea.docx
clarebernice
 
Consider the various ways to create effective communication in teams.docx
Consider the various ways to create effective communication in teams.docxConsider the various ways to create effective communication in teams.docx
Consider the various ways to create effective communication in teams.docx
clarebernice
 
consider the unique and varied forms of slaveryenslavement in Afric.docx
consider the unique and varied forms of slaveryenslavement in Afric.docxconsider the unique and varied forms of slaveryenslavement in Afric.docx
consider the unique and varied forms of slaveryenslavement in Afric.docx
clarebernice
 
Consider the types of digital technology advances that exist and how.docx
Consider the types of digital technology advances that exist and how.docxConsider the types of digital technology advances that exist and how.docx
Consider the types of digital technology advances that exist and how.docx
clarebernice
 
Consider the two following statements Photosynthesis and cellular .docx
Consider the two following statements Photosynthesis and cellular .docxConsider the two following statements Photosynthesis and cellular .docx
Consider the two following statements Photosynthesis and cellular .docx
clarebernice
 
Consider the study on Ethnography you described last week, Remind us.docx
Consider the study on Ethnography you described last week, Remind us.docxConsider the study on Ethnography you described last week, Remind us.docx
Consider the study on Ethnography you described last week, Remind us.docx
clarebernice
 
Consider the role of HR in a rapidly-changing world. What cha.docx
Consider the role of HR in a rapidly-changing world. What cha.docxConsider the role of HR in a rapidly-changing world. What cha.docx
Consider the role of HR in a rapidly-changing world. What cha.docx
clarebernice
 
Consider the scenarios involving the unwilling moral agents of J.docx
Consider the scenarios involving the unwilling moral agents of J.docxConsider the scenarios involving the unwilling moral agents of J.docx
Consider the scenarios involving the unwilling moral agents of J.docx
clarebernice
 
Consider the scenario below.A toxic waste dump company wants to .docx
Consider the scenario below.A toxic waste dump company wants to .docxConsider the scenario below.A toxic waste dump company wants to .docx
Consider the scenario below.A toxic waste dump company wants to .docx
clarebernice
 
Consider the role of interest groups in the policy-making process, w.docx
Consider the role of interest groups in the policy-making process, w.docxConsider the role of interest groups in the policy-making process, w.docx
Consider the role of interest groups in the policy-making process, w.docx
clarebernice
 
Consider the role of stakeholders in addressing a health problem a.docx
Consider the role of stakeholders in addressing a health problem a.docxConsider the role of stakeholders in addressing a health problem a.docx
Consider the role of stakeholders in addressing a health problem a.docx
clarebernice
 
Consider the quote by Adam Fuss in this module in which he describes.docx
Consider the quote by Adam Fuss in this module in which he describes.docxConsider the quote by Adam Fuss in this module in which he describes.docx
Consider the quote by Adam Fuss in this module in which he describes.docx
clarebernice
 
Consider the obstacles that Phoenix Jackson had to overcome on h.docx
Consider the obstacles that Phoenix Jackson had to overcome on h.docxConsider the obstacles that Phoenix Jackson had to overcome on h.docx
Consider the obstacles that Phoenix Jackson had to overcome on h.docx
clarebernice
 
Consider the nurse leader’s role in achieving the IHI Quadruple Ai.docx
Consider the nurse leader’s role in achieving the IHI Quadruple Ai.docxConsider the nurse leader’s role in achieving the IHI Quadruple Ai.docx
Consider the nurse leader’s role in achieving the IHI Quadruple Ai.docx
clarebernice
 
Consider the music business as a supply network. How has music d.docx
Consider the music business as a supply network. How has music d.docxConsider the music business as a supply network. How has music d.docx
Consider the music business as a supply network. How has music d.docx
clarebernice
 
Consider the mean of a cluster of objects from a binary transact.docx
Consider the mean of a cluster of objects from a binary transact.docxConsider the mean of a cluster of objects from a binary transact.docx
Consider the mean of a cluster of objects from a binary transact.docx
clarebernice
 
Consider the importance of using a variety of assessments in the.docx
Consider the importance of using a variety of assessments in the.docxConsider the importance of using a variety of assessments in the.docx
Consider the importance of using a variety of assessments in the.docx
clarebernice
 
Consider the importance of visuals in connecting with an audienc.docx
Consider the importance of visuals in connecting with an audienc.docxConsider the importance of visuals in connecting with an audienc.docx
Consider the importance of visuals in connecting with an audienc.docx
clarebernice
 
Consider the imagery you created in your mind as you interacted with.docx
Consider the imagery you created in your mind as you interacted with.docxConsider the imagery you created in your mind as you interacted with.docx
Consider the imagery you created in your mind as you interacted with.docx
clarebernice
 
Consider the followingContrast Soviet and post-Soviet migration.docx
Consider the followingContrast Soviet and post-Soviet migration.docxConsider the followingContrast Soviet and post-Soviet migration.docx
Consider the followingContrast Soviet and post-Soviet migration.docx
clarebernice
 

More from clarebernice (20)

Consider the vision for a successful Southwest Transit marketing tea.docx
Consider the vision for a successful Southwest Transit marketing tea.docxConsider the vision for a successful Southwest Transit marketing tea.docx
Consider the vision for a successful Southwest Transit marketing tea.docx
 
Consider the various ways to create effective communication in teams.docx
Consider the various ways to create effective communication in teams.docxConsider the various ways to create effective communication in teams.docx
Consider the various ways to create effective communication in teams.docx
 
consider the unique and varied forms of slaveryenslavement in Afric.docx
consider the unique and varied forms of slaveryenslavement in Afric.docxconsider the unique and varied forms of slaveryenslavement in Afric.docx
consider the unique and varied forms of slaveryenslavement in Afric.docx
 
Consider the types of digital technology advances that exist and how.docx
Consider the types of digital technology advances that exist and how.docxConsider the types of digital technology advances that exist and how.docx
Consider the types of digital technology advances that exist and how.docx
 
Consider the two following statements Photosynthesis and cellular .docx
Consider the two following statements Photosynthesis and cellular .docxConsider the two following statements Photosynthesis and cellular .docx
Consider the two following statements Photosynthesis and cellular .docx
 
Consider the study on Ethnography you described last week, Remind us.docx
Consider the study on Ethnography you described last week, Remind us.docxConsider the study on Ethnography you described last week, Remind us.docx
Consider the study on Ethnography you described last week, Remind us.docx
 
Consider the role of HR in a rapidly-changing world. What cha.docx
Consider the role of HR in a rapidly-changing world. What cha.docxConsider the role of HR in a rapidly-changing world. What cha.docx
Consider the role of HR in a rapidly-changing world. What cha.docx
 
Consider the scenarios involving the unwilling moral agents of J.docx
Consider the scenarios involving the unwilling moral agents of J.docxConsider the scenarios involving the unwilling moral agents of J.docx
Consider the scenarios involving the unwilling moral agents of J.docx
 
Consider the scenario below.A toxic waste dump company wants to .docx
Consider the scenario below.A toxic waste dump company wants to .docxConsider the scenario below.A toxic waste dump company wants to .docx
Consider the scenario below.A toxic waste dump company wants to .docx
 
Consider the role of interest groups in the policy-making process, w.docx
Consider the role of interest groups in the policy-making process, w.docxConsider the role of interest groups in the policy-making process, w.docx
Consider the role of interest groups in the policy-making process, w.docx
 
Consider the role of stakeholders in addressing a health problem a.docx
Consider the role of stakeholders in addressing a health problem a.docxConsider the role of stakeholders in addressing a health problem a.docx
Consider the role of stakeholders in addressing a health problem a.docx
 
Consider the quote by Adam Fuss in this module in which he describes.docx
Consider the quote by Adam Fuss in this module in which he describes.docxConsider the quote by Adam Fuss in this module in which he describes.docx
Consider the quote by Adam Fuss in this module in which he describes.docx
 
Consider the obstacles that Phoenix Jackson had to overcome on h.docx
Consider the obstacles that Phoenix Jackson had to overcome on h.docxConsider the obstacles that Phoenix Jackson had to overcome on h.docx
Consider the obstacles that Phoenix Jackson had to overcome on h.docx
 
Consider the nurse leader’s role in achieving the IHI Quadruple Ai.docx
Consider the nurse leader’s role in achieving the IHI Quadruple Ai.docxConsider the nurse leader’s role in achieving the IHI Quadruple Ai.docx
Consider the nurse leader’s role in achieving the IHI Quadruple Ai.docx
 
Consider the music business as a supply network. How has music d.docx
Consider the music business as a supply network. How has music d.docxConsider the music business as a supply network. How has music d.docx
Consider the music business as a supply network. How has music d.docx
 
Consider the mean of a cluster of objects from a binary transact.docx
Consider the mean of a cluster of objects from a binary transact.docxConsider the mean of a cluster of objects from a binary transact.docx
Consider the mean of a cluster of objects from a binary transact.docx
 
Consider the importance of using a variety of assessments in the.docx
Consider the importance of using a variety of assessments in the.docxConsider the importance of using a variety of assessments in the.docx
Consider the importance of using a variety of assessments in the.docx
 
Consider the importance of visuals in connecting with an audienc.docx
Consider the importance of visuals in connecting with an audienc.docxConsider the importance of visuals in connecting with an audienc.docx
Consider the importance of visuals in connecting with an audienc.docx
 
Consider the imagery you created in your mind as you interacted with.docx
Consider the imagery you created in your mind as you interacted with.docxConsider the imagery you created in your mind as you interacted with.docx
Consider the imagery you created in your mind as you interacted with.docx
 
Consider the followingContrast Soviet and post-Soviet migration.docx
Consider the followingContrast Soviet and post-Soviet migration.docxConsider the followingContrast Soviet and post-Soviet migration.docx
Consider the followingContrast Soviet and post-Soviet migration.docx
 

Recently uploaded

Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
melliereed
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
JomonJoseph58
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 

Recently uploaded (20)

Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 

CIS276DB Module 6 Assignment 1. Write a select sta.docx

  • 1. CIS276DB Module 6 Assignment 1. Write a select statement based on the InvoiceTotal column of the Invoices table: integer value. Name it IntTotal. Name it IntTotal. datatype decimal with one digit to the right. Name it DecimalTotal. datatype that outputs 2 digits to the right of the decimal point and all comma’s to the left (i.e. 3, 106.34). Name it FormatTotal. 2. Write a select statement that returns 4 columns based on the Vendors table: - Name): this column should be formatted in
  • 2. the following way; VendorContactFName followed by the last initial and a period (example: “John S.”). - StateInitial): the VendorState first initial in lowercase. - Phone): VendorPhone without the area code - TodaysDate): the current date formatted like- Apr 18, 2008 Filter the results to only return rows where the VendorPhone prefix is equal to ‘(800)’. Sort the results by VendorState and LastName. 3. Business Case: The current date is 12/1/2008; the accounting department would like to know which invoices with a balance due are still outstanding and the current age in days their invoice is beyond the invoice date. Write a select statement that returns 4 columns: VendorName, InvoiceTotal, InvoiceDate and InvoiceAge (use the appropriate function that will return the number of days between the InvoiceDate and ‘12/1/2008’). Filter the results to only return rows where there is a balance due and the
  • 3. InvoiceAge is greater than 132. Sort the results by VendorName. 4. Write a select statement that returns 7 columns: - WrittenDate): use the function that will convert InvoiceDate to this format; Apr 18, 2008 - NewDate): use the function that will add 45 days to InvoiceDate and convert it to this format; Apr 18, 2008 - DayOfWeek): Use the function that will return the name of the day of NewDate (i.e. Saturday) - MonthPart): Use the function that will return the name of the month of NewDate (i.e March) - DatePart): Use the function that will return the day date of NewDate (i.e. 18 {of Apr 18, 2008}) - YearPart): Use the function that will return the year from
  • 4. NewDate (i.e. 2008) Sort the results by InvoiceDate. 5. Business Case: The executive committee is implementing a purchase discount program based on the invoice total for a vendor. As such, they need to gauge how many invoices might qualify for a discount. Invoices that are below $100 will NOT qualify for a discount. Invoices between 101 and $500 are a low consideration, invoices between 501 and $1000 are a higher consideration and invoices above $1000 are the highest consideration. Write a select statement that returns 4 columns: VendorName, InvoiceNumber, InvoiceTotal, and PotentialDiscount. PotentialDiscount is a column that will contain the result expression from a CASE statement that contains 4 conditionals based on the InvoiceTotal column; Conditionals Result expression InvoiceTotal < 100 ‘No discount consideration’ InvoiceTotal 101-500 ‘Discount potential 3’ InvoiceTotal 501-1000 ‘Discount potential 2’ InvoiceTotal > 1000 ‘Discount potential 1’ Sort the results by InvoiceTotal.
  • 5. 6. Business Case: The accounting department would like to know the current balances for vendors that owe money on their accounts. They would like to categorize vendors who owe over $11,000 as having a Very High debt level, those who owe between $11,000 and over $500 as having a High debt level, those who owe between $500 and over $200 as having a Medium debt level and anyone else as a Low debt level. Write a select statement that returns 3 columns: function o Sum of Balances greater than $11,000 = ‘Very High’ o Sum of Balances between $11,000 and greater than $500 = ‘High’ o Sum of Balances between $500 and greater than $200 = ‘Medium’ o Sum of Balances equal to $200 or less = ‘Low’ Filter the results to only include vendors where a balance is due and sort the results from the sum of largest balance to smallest.
  • 6. To display a column where the data type cannot be implicitly converted, use a CAST function USE AP; SELECT InvoiceTotal, InvoiceDate, CAST(InvoiceTotal AS varchar) AS ITVc, CAST(InvoiceDate AS money) AS TimeIsMoney FROM Invoices CONVERT allows you to format certain datatypes (dates primarily) SELECT CONVERT(varchar, InvoiceDate) AS S1, CONVERT(varchar, InvoiceDate,1) AS S2, CONVERT(varchar, InvoiceDate,109) AS S3, CONVERT(varchar, InvoiceDate, 8) AS S4, CONVERT(varchar, InvoiceDate, 10) AS S5, CONVERT(varchar, InvoiceTotal, 1) AS M1, CONVERT(varchar, InvoiceTotal, 101) AS M2, CONVERT(varchar, InvoiceTotal, 53) AS M3 FROM Invoices Using carriage returns and line feeds (CHAR(13), CHAR(10)) you can output columns as text (example here- address label) USE AP SELECT VendorContactFName + ' ' + VendorContactLName + CHAR(13) + CHAR(10) + VendorAddress1 + CHAR(13) + CHAR(10) + VendorCity + ', ' + VendorState + ' ' + VendorZipCode + CHAR(13) FROM Vendors
  • 7. As it turns out, you don’t need the line feed! USE AP SELECT VendorContactFName + ' ' + VendorContactLName + CHAR(13) + VendorAddress1 + CHAR(13) + VendorCity + ', ' + VendorState + ' ' + VendorZipCode + CHAR(13) FROM Vendors String functions USE AP SELECT VendorName, LEN(vendorName) AS L, UPPER(VendorName) AS U, LOWER(VendorName) AS Lw, RIGHT(VendorName, 6) AS Rn, LEFT(VendorName, 6) AS Ln FROM Vendors String functions USE AP SELECT VendorAddress1, CHARINDEX('po', VendorAddress1) AS wiPO, PATINDEX('%in%', VendorAddress1) AS wiIN, REVERSE(VendorAddress1) AS scramble FROM Vendors String functions USE AP SELECT VendorPhone, REPLACE(RIGHT(VendorPhone, 13), ') ', '-') AS Noparenthesis, SUBSTRING(VendorPhone, 7,8) AS NoAreaCode, SUBSTRING(VendorPhone, 2,3) AS AreaCode
  • 8. FROM Vendors String functions USE Examples SELECT Name, LEFT(Name, CHARINDEX(' ', Name)-1) AS FirstName, RIGHT(Name, LEN(Name) - CHARINDEX(' ', Name)) AS LastName FROM StringSample Date functions using only GETDATE() SELECT GETDATE() AS TodaysDate, DAY(GETDATE()) AS CurrDay, MONTH(GETDATE()) AS CurrMonth, YEAR(GETDATE()) AS CurrYear, DATENAME(month, GETDATE()) AS MonthName Date functions USE AP SELECT InvoiceDate, InvoiceDate + 14 AS IDpTW, DATEDIFF(month, InvoiceDate, GETDATE()) AS DateDif, CONVERT(varchar, DATEADD(year, 9, InvoiceDate),107) AS DateAdd FROM Invoices Ranking functions USE AP SELECT NTILE(4) OVER (ORDER BY InvoiceTotal DESC) AS Rank, InvoiceTotal, InvoiceNumber FROM Invoices Ranking functions USE AP SELECT NTILE(10) OVER (ORDER BY InvoiceTotal DESC)
  • 9. AS Rank, InvoiceTotal, InvoiceNumber FROM Invoices Ranking functions USE AP SELECT RANK() OVER (ORDER BY InvoiceTotal) AS Rank, DENSE_RANK() OVER (ORDER BY InvoiceTotal) AS DenseRank, InvoiceTotal FROM Invoices Ranking functions USE AP SELECT ROW_NUMBER() OVER (PARTITION BY VendorState, VendorCity ORDER BY VendorName) AS RowNum, VendorName, VendorState, VendorCity FROM Vendors Case Function USE AP SELECT VendorName, InvoiceTotal, CASE WHEN InvoiceTotal > 5000 THEN 'We owe our souls' WHEN InvoiceTotal BETWEEN 1000 AND 5000 THEN 'Its ok' WHEN InvoiceTotal BETWEEN 100 AND 999 THEN 'much better' WHEN InvoiceTotal < 100 THEN 'awesome' END AS DebtType FROM Vendors v JOIN Invoices i ON V.VendorID = i.VendorID
  • 10. ORDER BY InvoiceTotal DESC Case Function USE AP SELECT InvoiceNumber, TermsID, CASE TermsID WHEN 1 THEN 'Net due 10 days' WHEN 2 THEN 'Net due 20 days' WHEN 3 THEN 'Net due 30 days' WHEN 4 THEN 'Net due 40 days' WHEN 5 THEN 'Net due 50 days' END AS Terms FROM Invoices ORDER BY Terms Case Function using GROUPING (this removes the NULL value that’s present in a summary query that uses a ROLLUP or CUBE operator) USE AP SELECT CASE WHEN GROUPING(VendorState) = 1 THEN 'All' ELSE VendorState END AS VendorState, CASE WHEN GROUPING(VendorCity) = 1 THEN 'All' ELSE VendorCity
  • 11. END AS VendorCity, COUNT(*) AS QtyVend FROM Vendors WHERE VendorState IN('IA', 'NJ') GROUP BY VendorState, VendorCity WITH ROLLUP ORDER BY VendorState DESC, VendorCity COALESCE removes null values that are present in columns- here using the left join between Vendors and Invoices- vendors that don’t have an Invoice (therefore don’t have an InvoiceTotal) will display NULL in the InvoiceTotal column. Using COALESCE, we can substitute a value for NULL (since InvoiceTotal is a money data type, we have to use a CAST function to substitute a varchar data type- ‘No Invoice Total’). USE AP SELECT VendorName, COALESCE(CAST(InvoiceTotal AS Varchar), 'No Invoice Total') AS InvoiceTotal FROM Vendors v LEFT JOIN Invoices i ON v.Vendorid = i.VendorID ORDER BY VendorName ISNULL works the same as COALESCE USE AP SELECT VendorName, ISNULL(CAST(InvoiceTotal AS Varchar), 'No Invoice Total') AS InvoiceTotal FROM Vendors v LEFT JOIN Invoices i ON v.Vendorid = i.VendorID ORDER BY VendorName For this ISNULL example, we substitute in a money value (0.00) so CAST isn’t necessary USE AP SELECT VendorName, ISNULL(InvoiceTotal, 0.00) AS InvoiceTotal
  • 12. FROM Vendors v LEFT JOIN Invoices i ON v.Vendorid = i.VendorID ORDER BY VendorName IIF Function USE AP SELECT InvoiceTotal, VendorState, IIF(InvoiceTotal>1500, 'High', 'Low') AS InvoiceValue, IIF(VendorState = 'CA', 'Cali Vendor', 'Not Cali') AS StateVendor FROM Vendors v JOIN Invoices i ON v.VendorID = i.vendorID Creating test tables for adding, modifying and deleting data USE AP SELECT * INTO Invoice1 FROM Invoices Creating test tables for adding, modifying and deleting data USE AP SELECT * INTO Vendor1 FROM Vendors Creating test tables for adding, modifying and deleting data (partial table) USE AP SELECT * INTO Invoice2 FROM Invoices WHERE InvoiceTotal-PaymentTotal-CreditTotal = 0 INSERT statement that only uses a VALUE list
  • 13. USE AP INSERT INTO Invoice2 VALUES(1, '123456', '1/1/2016', 100.00, 0, 0, 1, '1/10/2016', NULL) INSERT statement that uses a COLUMN list along with several VALUE lists USE AP INSERT INTO Invoice2 (InvoiceNumber, VendorID, InvoiceDate, InvoiceTotal,PaymentTotal, CreditTotal, InvoiceDueDate, TermsID) VALUES('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1), ('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1), ('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1), ('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1), ('234567', 6, '2/1/2016', 500.00, 0, 0, '2/10/2016', 1) INSERT statement that uses a subquery USE AP INSERT INTO Invoice1 (VendorID, InvoiceTotal, InvoiceNumber, CreditTotal, TermsID, PaymentTotal, InvoiceDate, InvoiceDueDate) SELECT VendorID, InvoiceTotal, InvoiceNumber, CreditTotal, TermsID, PaymentTotal, InvoiceDate, InvoiceDueDate FROM Invoices WHERE InvoiceTotal > 100 UPDATE statement (UPDATES REQUIRE A WHERE!)
  • 14. USE AP UPDATE Invoice2 SET PaymentDate = '1/14/2016', PaymentTotal = PaymentTotal + 100 WHERE InvoiceNumber = '123456' UPDATE statement (UPDATES REQUIRE A WHERE!) USE AP UPDATE Invoice1 SET CreditTotal = CreditTotal + 4.50 WHERE VendorID = (SELECT VendorID FROM Vendor1 WHERE VendorName = 'Blue Cross') DELETE statement (DELETES REQUIRE A WHERE!) USE AP DELETE Invoice1 WHERE InvoiceID = 4 DROP Table syntax (forgot to do this in class DROP TABLE Invoice1 DROP TABLE Invoice2 DROP TABLE vendor1 Databases/AP.mdf Databases/AP_AllObjects.mdf Databases/AP_AllObjects_log.LDF Databases/AP_log.LDF Databases/Examples.mdf