compsci-notes-spring-2024/notes/database-prog/sql-scripts/2024-01-31.sql

62 lines
2.5 KiB
SQL

-- #### Start of class stuff ####
-- Get the InvoiceID, InvoiceTotal, and InvoiceDueDate for all invoices for vendor 110
SELECT InvoiceID, InvoiceTotal, InvoiceDueDate
FROM Invoices
WHERE VendorID = 110
-- Get the latest 10 invoices for vendor 123: InvoiceID, InvoiceDueDate, InvoiceTotal
SELECT TOP 10 InvoiceID, InvoiceTotal, InvoiceDueDate
FROM Invoices
WHERE VendorID = 123
ORDER BY InvoiceDueDate DESC
-- Get the InvoiceID, VendorID, InvoiceDueDate, and InvoiceTotal for all invoices due between 1/1/2020 and 1/31/2020
SELECT InvoiceID, VendorID, InvoiceDueDate, InvoiceTotal
FROM Invoices
WHERE InvoiceDueDate BETWEEN '1/1/2020' AND '1/31/2020'
-- ######################################################################## --
-- Get top 10 unpaid invoices
SELECT TOP 10 InvoiceID, VendorID, InvoiceTotal, InvoiceDueDate FROM Invoices
WHERE PaymentDate IS NULL
ORDER BY InvoiceDueDate
SELECT VendorID, VendorName, VendorContactLName, VendorContactFName FROM Vendors
WHERE VendorID IN (72, 83, 80, 123, 110, 106, 37) -- Output from last query
-- Combine them with JOIN
SELECT TOP 10 InvoiceID, Invoices.VendorID, InvoiceTotal, InvoiceDueDate, VendorName, VendorContactLName, VendorContactFName
FROM Invoices
JOIN Vendors ON Invoices.VendorID = Vendors.VendorID
WHERE PaymentDate IS NULL
ORDER BY InvoiceDueDate
-- Get all vendors with invoices
-- inter-JOINs only return rows that match on both tables
SELECT DISTINCT v.VendorID, VendorName FROM Vendors v
JOIN Invoices i ON v.VendorID = i.VendorID
-- Outer-JOIN: Returns all of a table plus anything in the other
-- Get all vendors and invoices if they have any
SELECT v.VendorID, VendorName, InvoiceID FROM Vendors v
LEFT JOIN Invoices i ON v.VendorID = i.VendorID
-- LEFT or RIGHT determines which is the "main one" that the other is joined to
-- CROSS JOIN - combine the tables???
SELECT v.VendorID, VendorName, InvoiceId
FROM Vendors v CROSS JOIN Invoices i
ORDER BY VendorID
-- Get employees and their managers
SELECT e.EmployeeID, e.LastName, e.FirstName, m.FirstName + ' ' + m.LastName ManagerName
FROM Employees e JOIN Employees m ON e.ManagerID = m.EmployeeID
-- Customers table has FK Cities, Cities FK State, State FK Countries
-- To get full address of customers
SELECT c.CustomerId, c.CustomerName, PostalAddressLine1, ci.CityName, sp.StateProvinceName, cty.CountryName
FROM Sales.Customers c
LEFT JOIN application.Cities ci ON c.DeliveryCityID = ci.CityID
JOIN application.StateProvinces sp ON sp.StateProvinceID = ci.StateProvinceID
JOIN application.Countries cty ON cty.CountryID = sp.CountryID