Name: Abdul Rahman
Sap id: 54633
Subject: Database System
Section: BSCS-3A
Miss: Riva Malik
Lab no 8
Task no 1:
Write a correlated subquery to display Invoice Id, Billing city billing state and total sales in descending
order. Hint: One Sale= unitprice* quantity
Query:
SELECT
i.InvoiceId,
i.BillingCity,
i.BillingState,
(SELECT SUM(inl.UnitPrice * inl.Quantity)
FROM InvoiceLine inl
WHERE inl.InvoiceId = i.InvoiceId) AS TotalSales
FROM
Invoice i
ORDER BY
TotalSales DESC;
Task no 2:
Write a correlated subquery to display invoice information having latest date
Query:
SELECT *
FROM Invoice i2
WHERE i2.InvoiceDate = (
SELECT MAX(i.InvoiceDate)
FROM Invoice i
);
Task no 3:
Write correlated subquery to display Customers(customer Id, full name, email address) who placed
orders greater than their average order amount.
Query:
SELECT
c.CustomerId,
CONCAT(c.FirstName, ' ', c.LastName) AS FullName,
c.Email
FROM
Customer c
WHERE
(SELECT SUM(i.Total)
FROM Invoice i
WHERE i.CustomerId = c.CustomerId) >
(SELECT AVG(i2.Total)
FROM Invoice i2
WHERE i2.CustomerId = c.CustomerId);
Task no 4:
Write query to list all albums with track longer than the average track length in database
Query:
SELECT DISTINCT
A.AlbumId,
A.Title,
AR.Name AS ArtistName
FROM
Album A
JOIN
Track T ON A.AlbumId = T.AlbumId
JOIN
Artist AR ON A.ArtistId = AR.ArtistId
WHERE
T.Milliseconds > (
SELECT AVG(T2.Milliseconds)
FROM Track T2
WHERE T2.AlbumId = T.AlbumId
);