SQL Code
SQL Code
USE PUBS;
SELECT * FROM titles;
SELECT title,ytd_sales FROM titles WHERE ytd_sales > 8000;
#Discussion 1 Task 2
USE PUBS;
SELECT * FROM titles;
SELECT title,royalty FROM titles WHERE royalty>12 AND royalty<24;
#Discussion 1 Task 3
USE PUBS;
SELECT * FROM titles;
SELECT type,AVG(price) AveragePrice,SUM(ytd_sales) TotalYearlySales
FROM titles GROUP BY type;
#Discussion 2 Task 2
USE PUBS;
SELECT CONCAT(au_fname,' ',au_lname) AS
AuthorName,authors.city,pub_name FROM
authors,publishers WHERE authors.city = publishers.city;
Another method
USE PUBS;
SELECT CONCAT(au_fname,' ',au_lname) AS
AuthorName,authors.city,pub_name FROM
authors JOIN publishers ON authors.city = publishers.city;
#Discussion 2 Task 3
USE PUBS;
SELECT title,CONCAT(au_fname,' ',au_lname)
AS AuthorName,royalty FROM authors JOIN titleauthor
ON authors.au_id = titleauthor.au_id JOIN titles
ON titleauthor.title_id =titles.title_id
WHERE royalty = (SELECT MAX(royalty) FROM titles);
#Discussion 3 Task 1
USE Assignment;
GO
CREATE PROCEDURE printDetails
AS
BEGIN
SELECT item_category,SUM(item_qoh) AS TotalItem,AVG(item_price) AS
newAvgPrice FROM Item GROUP BY item_category
END
EXEC printDetails;
#Discussion 3 Task 2
USE Assignment;
GO
CREATE PROCEDURE printDetails1 @itemCategory CHAR(10),@itemPrice
INT
AS
BEGIN
SELECT * FROM Item WHERE item_category = @itemCategory AND
item_price<@itemPrice
END
#Discussion 3 Task 3
USE Assignment;
GO
CREATE PROCEDURE printDetails2 @itemCategory
CHAR(10),@desiredAvgValue FLOAT
AS
BEGIN
DECLARE @totalPrice DECIMAL(10,2),@totalItem INT,@currentAvgPrice
FLOAT
SELECT @totalPrice = SUM(item_price),@totalItem = COUNT(*) FROM Item
WHERE item_category = @itemCategory
SET @currentAvgPrice = @totalPrice/@totalItem
WHILE @currentAvgPrice<@desiredAvgValue
BEGIN
UPDATE Item
SET item_price = item_price + 0.1*(item_price) WHERE item_category =
@itemCategory
SELECT @totalPrice = SUM(item_price) FROM Item WHERE item_category =
@itemCategory
SET @currentAvgPrice = @totalPrice/@totalItem
END
SELECT item_category,AVG(item_price) newAvgPrice FROM Item WHERE
item_category = @itemCategory
GROUP BY item_category
END
#Discussion 4 Task 1
USE Assignment;
GO
CREATE TRIGGER updateAmounts ON Transactions AFTER INSERT
AS
BEGIN
DECLARE @tranType CHAR(1)
DECLARE @tranQuantity INT
DECLARE @itemPrice DECIMAL(10,2)
DECLARE @custID CHAR(6)
SELECT @tranType = tran_type,@tranQuantity = tran_quantity,@custID =
cust_id FROM INSERTED
IF (@tranType = 'S')
BEGIN
SELECT @itemPrice = item_price FROM Item WHERE item_id IN (SELECT
item_id FROM INSERTED)
UPDATE CustomerAndSuppliers
SET sales_amnt = sales_amnt + (@itemPrice*@tranQuantity) WHERE cust_id =
@custID
END
IF (@tranType = 'O')
BEGIN
SELECT @itemPrice = item_price FROM Item WHERE item_id IN (SELECT
item_id FROM INSERTED)
UPDATE CustomerAndSuppliers
SET proc_amnt = proc_amnt + (@itemPrice*@tranQuantity) WHERE cust_id =
@custID
END
END