SQL Queries To Generate Reports
SQL Queries To Generate Reports
Select
[SalesLT].[Customer].[CompanyName],[SalesLT].[SalesOrderHeader].[SalesOrderID],[SalesLT].
[SalesOrderHeader].[TotalDue],
[SalesLT].[Address].[AddressLine1] +
isnull([SalesLT].[Address].[AddressLine2],'')+','+[SalesLT].[Address].[City]+' '+
[SalesLT].[Address].[StateProvince]+','+[SalesLT].[Address].[CountryRegion]+ '-
'+[SalesLT].[Address].[PostalCode]
AS MainOfficeAddress from [SalesLT].[Customer]
inner join [SalesLT].[SalesOrderHeader]
on [SalesLT].[Customer].[CustomerID]=[SalesLT].[SalesOrderHeader].[CustomerID]
inner join[SalesLT].[CustomerAddress]
on [SalesLT].[Customer].[CustomerID] = [SalesLT].[CustomerAddress].CustomerID
inner join [SalesLT].[Address]
on [SalesLT].[CustomerAddress].AddressID = [SalesLT].[Address].AddressID;
Challenge 2: Retrieve Sales Data
As you continue to work with the Adventure Works customer and sales data, you must create queries
for reports that have been requested by the sales team.
1. Retrieve a list of all customers and their orders
The sales manager wants a list of all customer companies and their contacts (first name and last name),
showing the sales order ID and total due for each order they have placed. Customers who have not
placed any orders should be included at the bottom of the list with NULL values for the order ID and
total due.
Select [SalesLT].[Customer].[CompanyName],([SalesLT].[Customer].FirstName +
[SalesLT].[Customer].LastName) AS Contacts,
[SalesLT].[SalesOrderHeader].[SalesOrderID], [SalesLT].[SalesOrderHeader].[TotalDue]
from [SalesLT].[Customer] Left outer join [SalesLT].[SalesOrderHeader]
on [SalesLT].[Customer].[CustomerID] =[SalesLT].[SalesOrderHeader].[CustomerID]
order by [SalesLT].[SalesOrderHeader].[TotalDue]
Desc,[SalesLT].[SalesOrderHeader].[SalesOrderID]
2. Retrieve only customers with both a main office address and a shipping address
Write a query that returns the company name of each company that appears in a table of customers
with a Main Office address, and also in a table of customers with a Shipping address.
SELECT c.CompanyName
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Main Office'
INTERSECT
SELECT c.CompanyName
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Shipping'
ORDER BY c.CompanyName;