0% found this document useful (0 votes)
3 views

Schema Question

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Schema Question

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

1.

Find students who are enrolled in more than 5 courses in the current
semester.

sql
Copy code
SELECT s.student_id, s.name, COUNT(e.course_id) AS course_count
FROM Students s
JOIN Enrollments e ON s.student_id = e.student_id
JOIN Classes c ON e.class_id = c.class_id
WHERE c.semester = 'Spring' AND c.year = 2024
GROUP BY s.student_id, s.name
HAVING course_count > 5;

2. Retrieve the names of professors who are teaching classes with more than 100
students.

sql
Copy code
SELECT p.professor_id, p.name, COUNT(e.student_id) AS student_count
FROM Professors p
JOIN Classes c ON p.professor_id = c.professor_id
JOIN Enrollments e ON c.class_id = e.class_id
GROUP BY p.professor_id, p.name
HAVING student_count > 100;
3. List all courses that do not have any prerequisites.

sql
Copy code
SELECT c.course_id, c.course_name
FROM Courses c
LEFT JOIN Course_Prerequisites cp ON c.course_id = cp.course_id
WHERE cp.prerequisite_course_id IS NULL;

4. Find the average grade for each course in the current semester.

sql
Copy code
SELECT c.course_id, c.course_name, AVG(g.grade) AS avg_grade
FROM Courses c
JOIN Classes cl ON c.course_id = cl.course_id
JOIN Enrollments e ON cl.class_id = e.class_id
JOIN Grades g ON e.enrollment_id = g.enrollment_id
WHERE cl.semester = 'Spring' AND cl.year = 2024
GROUP BY c.course_id, c.course_name;

5. Retrieve the schedule of classes that are held in rooms with a capacity greater
than 50.

sql
Copy code
SELECT r.building, r.room_number, cs.day, cs.start_time, cs.end_time
FROM Rooms r
JOIN Class_Schedules cs ON r.room_id = cs.room_id
WHERE r.capacity > 50;

6. List students who have never received a grade below 'B'.

sql
Copy code
SELECT DISTINCT s.student_id, s.name
FROM Students s
JOIN Enrollments e ON s.student_id = e.student_id
JOIN Grades g ON e.enrollment_id = g.enrollment_id
WHERE g.grade NOT IN ('C', 'D', 'F');

7. Find the departments that have professors teaching more than 5 different
courses.

sql
Copy code
SELECT d.department_id, d.department_name, COUNT(DISTINCT c.course_id) AS
course_count
FROM Departments d
JOIN Professors p ON d.department_id = p.department_id
JOIN Classes cl ON p.professor_id = cl.professor_id
JOIN Courses c ON cl.course_id = c.course_id
GROUP BY d.department_id, d.department_name
HAVING course_count > 5;
8. Retrieve the details of classes that are scheduled on Mondays and Wednesdays.

sql
Copy code
SELECT cl.class_id, c.course_name, cs.day, cs.start_time, cs.end_time
FROM Classes cl
JOIN Courses c ON cl.course_id = c.course_id
JOIN Class_Schedules cs ON cl.class_id = cs.class_id
WHERE cs.day IN ('Monday', 'Wednesday');

9. List students who have never enrolled in courses outside their department.

sql
Copy code
SELECT s.student_id, s.name
FROM Students s
JOIN Enrollments e ON s.student_id = e.student_id
JOIN Courses c ON e.course_id = c.course_id
WHERE s.department_id = c.department_id
GROUP BY s.student_id, s.name;

10. Find the total number of credits for each student in the current semester.

sql
Copy code
SELECT s.student_id, s.name, SUM(c.credits) AS total_credits
FROM Students s
JOIN Enrollments e ON s.student_id = e.student_id
JOIN Classes cl ON e.class_id = cl.class_id
JOIN Courses c ON cl.course_id = c.course_id
WHERE cl.semester = 'Spring' AND cl.year = 2024
GROUP BY s.student_id, s.name;
1. Retrieve the list of users who have placed orders but never wrote any
reviews.
sql
Copy code
SELECT u.user_id, u.username
FROM Users u
JOIN Orders o ON u.user_id = o.user_id
LEFT JOIN Reviews r ON u.user_id = r.user_id
WHERE r.user_id IS NULL;

2. Find the top 5 products with the highest average rating, along with their
average rating.
sql
Copy code
SELECT p.product_id, p.product_name, AVG(r.rating) AS avg_rating
FROM Products p
JOIN Reviews r ON p.product_id = r.product_id
GROUP BY p.product_id, p.product_name
ORDER BY avg_rating DESC
LIMIT 5;

3. List the categories that have more than 50 products.


sql
Copy code
SELECT c.category_id, c.category_name, COUNT(p.product_id) AS product_count
FROM Categories c
JOIN Products p ON c.category_id = p.category_id
GROUP BY c.category_id, c.category_name
HAVING product_count > 50;
4. Retrieve the order details, including the total amount, for orders placed by
users from a specific city (e.g., 'New York').
sql
Copy code
SELECT o.order_id, o.order_date, SUM(oi.quantity * oi.price) AS
total_amount
FROM Orders o
JOIN Order_Items oi ON o.order_id = oi.order_id
JOIN Users u ON o.user_id = u.user_id
JOIN Addresses a ON u.user_id = a.user_id
WHERE a.city = 'New York'
GROUP BY o.order_id, o.order_date;

5. Find the suppliers who supply more than 10 different products.


sql
Copy code
SELECT s.supplier_id, s.supplier_name, COUNT(DISTINCT ps.product_id) AS
product_count
FROM Suppliers s
JOIN Product_Supplier ps ON s.supplier_id = ps.supplier_id
GROUP BY s.supplier_id, s.supplier_name
HAVING product_count > 10;

6. Retrieve the top 3 most frequently ordered products.


sql
Copy code
SELECT p.product_id, p.product_name, COUNT(oi.product_id) AS order_count
FROM Products p
JOIN Order_Items oi ON p.product_id = oi.product_id
GROUP BY p.product_id, p.product_name
ORDER BY order_count DESC
LIMIT 3;

7. List all users who have placed orders totaling over $1000.
sql
Copy code
SELECT u.user_id, u.username, SUM(oi.quantity * oi.price) AS total_spent
FROM Users u
JOIN Orders o ON u.user_id = o.user_id
JOIN Order_Items oi ON o.order_id = oi.order_id
GROUP BY u.user_id, u.username
HAVING total_spent > 1000;

8. Find the average rating for products in each category.


sql
Copy code
SELECT c.category_id, c.category_name, AVG(r.rating) AS avg_rating
FROM Categories c
JOIN Products p ON c.category_id = p.category_id
JOIN Reviews r ON p.product_id = r.product_id
GROUP BY c.category_id, c.category_name;

9. List orders that include products from more than one category.
sql
Copy code
SELECT o.order_id
FROM Orders o
JOIN Order_Items oi ON o.order_id = oi.order_id
JOIN Products p ON oi.product_id = p.product_id
JOIN Categories c ON p.category_id = c.category_id
GROUP BY o.order_id
HAVING COUNT(DISTINCT c.category_id) > 1;

10. Retrieve the details of products that have never been ordered.
sql
Copy code
SELECT p.product_id, p.product_name, p.description, p.price
FROM Products p
LEFT JOIN Order_Items oi ON p.product_id = oi.product_id
WHERE oi.product_id IS NULL;
1. Retrieve the list of doctors who have appointments scheduled
for a specific date.
sql
Copy code
SELECT DISTINCT d.doctor_id, d.first_name, d.last_name
FROM DOCTOR d
JOIN APPOINTMENT a ON d.doctor_id = a.doctor_id
WHERE DATE(a.appointment_datetime) = '2024-07-12';

2. Find patients who have been prescribed medication for more than 30
days in total.
sql
Copy code
SELECT p.patient_id, p.first_name, p.last_name, SUM(DATEDIFF(pr.end_date,
pr.start_date)) AS total_days
FROM PATIENT p
JOIN MEDICAL_RECORD mr ON p.patient_id = mr.patient_id
JOIN PRESCRIPTION pr ON mr.record_id = pr.record_id
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING total_days > 30;

3. List all patients who have never had an appointment.


sql
Copy code
SELECT p.patient_id, p.first_name, p.last_name
FROM PATIENT p
LEFT JOIN APPOINTMENT a ON p.patient_id = a.patient_id
WHERE a.appointment_id IS NULL;

4. Find the doctors who belong to the "Cardiology" department and have
more than 5 appointments in the last month.
sql
Copy code
SELECT d.doctor_id, d.first_name, d.last_name, COUNT(a.appointment_id) AS
appointment_count
FROM DOCTOR d
JOIN DEPARTMENT dep ON d.department_id = dep.department_id
JOIN APPOINTMENT a ON d.doctor_id = a.doctor_id
WHERE dep.name = 'Cardiology' AND a.appointment_datetime >= DATE_SUB(NOW(),
INTERVAL 1 MONTH)
GROUP BY d.doctor_id, d.first_name, d.last_name
HAVING appointment_count > 5;

5. Retrieve the list of patients along with their insurance details, if


available.
sql
Copy code
SELECT p.patient_id, p.first_name, p.last_name, i.provider_name,
i.policy_number
FROM PATIENT p
LEFT JOIN INSURANCE i ON p.patient_id = i.patient_id;

6. Find the most frequently prescribed medication.


sql
Copy code
SELECT m.name, COUNT(pr.prescription_id) AS prescription_count
FROM MEDICATION m
JOIN PRESCRIPTION pr ON m.medication_id = pr.medication_id
GROUP BY m.name
ORDER BY prescription_count DESC
LIMIT 1;

7. List all laboratory tests for a specific patient and include the test
results.
sql
Copy code
SELECT lt.test_name, lt.test_date, lt.results
FROM LABORATORY_TEST lt
JOIN MEDICAL_RECORD mr ON lt.record_id = mr.record_id
JOIN PATIENT p ON mr.patient_id = p.patient_id
WHERE p.patient_id = 12345;

8. Retrieve the total amount billed to each patient.


sql
Copy code
SELECT p.patient_id, p.first_name, p.last_name, SUM(b.amount) AS
total_billed
FROM PATIENT p
JOIN BILLING b ON p.patient_id = b.patient_id
GROUP BY p.patient_id, p.first_name, p.last_name;

9. Find the average number of appointments per doctor per month in the
current year.
sql
Copy code
SELECT d.doctor_id, d.first_name, d.last_name, AVG(monthly_appointments) AS
avg_monthly_appointments
FROM (
SELECT a.doctor_id, COUNT(a.appointment_id) AS monthly_appointments,
MONTH(a.appointment_datetime) AS month
FROM APPOINTMENT a
WHERE YEAR(a.appointment_datetime) = YEAR(NOW())
GROUP BY a.doctor_id, MONTH(a.appointment_datetime)
) AS monthly_data
JOIN DOCTOR d ON monthly_data.doctor_id = d.doctor_id
GROUP BY d.doctor_id, d.first_name, d.last_name;

10. List all appointments for patients who have insurance from a specific
provider.
sql
Copy code
SELECT a.appointment_id, a.appointment_datetime, p.first_name, p.last_name,
d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM APPOINTMENT a
JOIN PATIENT p ON a.patient_id = p.patient_id
JOIN DOCTOR d ON a.doctor_id = d.doctor_id
JOIN INSURANCE i ON p.patient_id = i.patient_id
WHERE i.provider_name = 'InsuranceProviderName';
 Find the average delay time for all trains arriving at a specific station in the last
month.

sql
Copy code
SELECT s.name AS station_name, AVG(TIMESTAMPDIFF(MINUTE,
sc.scheduled_arrival_time, sc.actual_arrival_time)) AS avg_delay
FROM Stations s
JOIN Schedules sc ON s.station_id = sc.arrival_station_id
WHERE sc.actual_arrival_time IS NOT NULL
AND sc.scheduled_arrival_time BETWEEN CURDATE() - INTERVAL 1 MONTH AND
CURDATE()
GROUP BY s.station_id, s.name;

 List all trains that have traveled more than a specific distance (e.g., 500 miles) in a
single journey.

sql
Copy code
SELECT t.train_id, t.train_name, SUM(r.distance) AS total_distance
FROM Trains t
JOIN Routes r ON t.train_id = r.train_id
GROUP BY t.train_id, t.train_name
HAVING total_distance > 500;
 Find passengers who have booked tickets on multiple trains in a single day.

sql
Copy code
SELECT p.passenger_id, p.name, COUNT(DISTINCT b.train_id) AS train_count
FROM Passengers p
JOIN Bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_date = '2024-07-20'
GROUP BY p.passenger_id, p.name
HAVING train_count > 1;

 List the most frequently traveled routes for each train in the past year.

sql
Copy code
SELECT t.train_id, t.train_name, r.route_id, COUNT(r.route_id) AS
travel_count
FROM Trains t
JOIN Routes r ON t.train_id = r.train_id
JOIN Schedules sc ON t.train_id = sc.train_id
WHERE sc.departure_time BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
GROUP BY t.train_id, t.train_name, r.route_id
ORDER BY travel_count DESC;

 Find all employees who have never received a promotion.

sql
Copy code
SELECT e.employee_id, e.name, e.position
FROM Employees e
LEFT JOIN Promotions p ON e.employee_id = p.employee_id
WHERE p.promotion_id IS NULL;

 Calculate the total revenue generated from first-class tickets for each train.

sql
Copy code
SELECT t.train_id, t.train_name, SUM(ti.price) AS total_revenue
FROM Trains t
JOIN Bookings b ON t.train_id = b.train_id
JOIN Tickets ti ON b.booking_id = ti.booking_id
WHERE ti.class = 'First Class'
GROUP BY t.train_id, t.train_name;

 Find the average number of stops made by trains on a specific route.

sql
Copy code
SELECT r.route_id, AVG(stop_count) AS avg_stops
FROM (
SELECT r.route_id, COUNT(r.stop_number) AS stop_count
FROM Routes r
GROUP BY r.route_id
) AS route_stops
GROUP BY r.route_id;
 Identify passengers who have booked tickets on more than one train in the last 6
months.

sql
Copy code
SELECT p.passenger_id, p.name, COUNT(DISTINCT b.train_id) AS train_count
FROM Passengers p
JOIN Bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_date BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE()
GROUP BY p.passenger_id, p.name
HAVING train_count > 1;

 List the trains that have had the highest number of cancellations in the past year.

sql
Copy code
SELECT t.train_id, t.train_name, COUNT(b.booking_id) AS cancellation_count
FROM Trains t
JOIN Bookings b ON t.train_id = b.train_id
WHERE b.status = 'Cancelled'
AND b.journey_date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
GROUP BY t.train_id, t.train_name
ORDER BY cancellation_count DESC;

 Calculate the total salary paid to employees in each department in the past year.

sql
Copy code
SELECT d.department_name, SUM(e.salary) AS total_salary
FROM Departments d
JOIN Employees e ON d.department_id = e.department_id
WHERE e.hire_date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
GROUP BY d.department_name;

 Find the total distance traveled by each train for journeys completed in the last
month.

sql
Copy code
SELECT t.train_id, t.train_name, SUM(r.distance) AS total_distance
FROM Trains t
JOIN Routes r ON t.train_id = r.train_id
JOIN Schedules sc ON t.train_id = sc.train_id
WHERE sc.arrival_time BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()
GROUP BY t.train_id, t.train_name;

 List all passengers who have traveled on trains of a specific type (e.g., 'Express') and
their total journey distances.

SELECT p.passenger_id, p.name, SUM(r.distance) AS total_distance


FROM Passengers p
JOIN Bookings b ON p.passenger_id = b.passenger_id
JOIN Trains t ON b.train_id = t.train_id
JOIN Routes r ON t.train_id = r.train_id
WHERE t.train_type = 'Express'
GROUP BY p.passenger_id, p.name;
 Find the average delay time for all trains arriving at a specific station in the last
month.

SELECT s.name AS station_name, AVG(TIMESTAMPDIFF(MINUTE,


sc.scheduled_arrival_time, sc.actual_arrival_time)) AS avg_delay
FROM Stations s
JOIN Schedules sc ON s.station_id = sc.arrival_station_id
WHERE sc.actual_arrival_time IS NOT NULL
AND sc.scheduled_arrival_time BETWEEN CURDATE() - INTERVAL 1 MONTH AND
CURDATE()
GROUP BY s.station_id, s.name;

 List the total revenue generated from each class of tickets for each train.

SELECT t.train_id, t.train_name, ti.class, SUM(ti.price) AS total_revenue


FROM Trains t
JOIN Bookings b ON t.train_id = b.train_id
JOIN Tickets ti ON b.booking_id = ti.booking_id
GROUP BY t.train_id, t.train_name, ti.class;

 Find all employees who have been assigned to trains that have had more than five
cancellations in the past year.

SELECT e.employee_id, e.name, COUNT(b.booking_id) AS cancellation_count


FROM Employees e
JOIN Departments d ON e.department_id = d.department_id
JOIN Trains t ON d.department_id = t.department_id
JOIN Bookings b ON t.train_id = b.train_id
WHERE b.status = 'Cancelled'
AND b.journey_date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
GROUP BY e.employee_id, e.name
HAVING cancellation_count > 5;

 List the most frequently used routes by each train, and the total number of stops
made on these routes.

SELECT t.train_id, t.train_name, r.route_id, COUNT(r.stop_number) AS


stop_count
FROM Trains t
JOIN Routes r ON t.train_id = r.train_id
GROUP BY t.train_id, t.train_name, r.route_id
ORDER BY stop_count DESC;

 Identify passengers who have booked tickets on multiple trains in the last 6 months
and their total number of journeys.

SELECT p.passenger_id, p.name, COUNT(DISTINCT b.train_id) AS train_count,


COUNT(b.booking_id) AS journey_count
FROM Passengers p
JOIN Bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_date BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE()
GROUP BY p.passenger_id, p.name
HAVING train_count > 1;
 Calculate the total salary paid to employees in each department and the number of
employees in the past year.

SELECT d.department_name, SUM(e.salary) AS total_salary,


COUNT(e.employee_id) AS employee_count
FROM Departments d
JOIN Employees e ON d.department_id = e.department_id
WHERE e.hire_date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
GROUP BY d.department_name;

 Find the total number of tickets sold and total revenue generated for each class of
tickets for journeys completed in the last month.

SELECT ti.class, COUNT(ti.ticket_id) AS total_tickets, SUM(ti.price) AS


total_revenue
FROM Tickets ti
JOIN Bookings b ON ti.booking_id = b.booking_id
JOIN Schedules sc ON b.train_id = sc.train_id
WHERE sc.arrival_time BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()
GROUP BY ti.class;

 List the trains that have traveled the maximum number of routes in the past year,
along with the number of routes.

SELECT t.train_id, t.train_name, COUNT(DISTINCT r.route_id) AS route_count


FROM Trains t
JOIN Routes r ON t.train_id = r.train_id
JOIN Schedules sc ON t.train_id = sc.train_id
WHERE sc.departure_time BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
GROUP BY t.train_id, t.train_name
ORDER BY route_count DESC;
 List all customers who have made payments towards loans and also have investments
in more than two different types.

SELECT c.customer_id, c.first_name, c.last_name


FROM Customers c
JOIN Loans l ON c.customer_id = l.customer_id
JOIN Payments p ON l.loan_id = p.loan_id
JOIN Investments i ON c.customer_id = i.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT i.investment_type) > 2;

 Retrieve the details of customers who have subscribed to more than 3 bank services
and have a total balance greater than $10,000 across all their accounts.

SELECT c.customer_id, c.first_name, c.last_name, SUM(a.balance) AS


total_balance
FROM Customers c
JOIN ServicesSubscriptions ss ON c.customer_id = ss.customer_id
JOIN Accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT ss.service_id) > 3 AND total_balance > 10000;

 Find all employees who manage accounts with an average balance greater than $5000,
including their branch and department details.

SELECT e.employee_id, e.first_name, e.last_name, b.branch_name,


d.department_name, AVG(a.balance) AS average_balance
FROM Employees e
JOIN AccountManagers am ON e.employee_id = am.employee_id
JOIN Accounts a ON am.account_id = a.account_id
JOIN Branches b ON e.branch_id = b.branch_id
JOIN Departments d ON e.department_id = d.department_id
GROUP BY e.employee_id, e.first_name, e.last_name, b.branch_name,
d.department_name
HAVING average_balance > 5000;

 List all ATM transactions where the account holder has an active loan and has made
at least one loan payment in the past month.

sql
Copy code
SELECT at.atm_transaction_id, at.transaction_date, at.amount,
c.customer_id, c.first_name, c.last_name
FROM ATMTransactions at
JOIN Accounts a ON at.account_id = a.account_id
JOIN Customers c ON a.customer_id = c.customer_id
JOIN Loans l ON c.customer_id = l.customer_id
JOIN Payments p ON l.loan_id = p.loan_id
WHERE p.payment_date >= CURDATE() - INTERVAL 1 MONTH;

 Retrieve the branch and department details for employees who have processed
transactions totaling more than $50,000 in the last 6 months.

sql
Copy code
SELECT e.employee_id, e.first_name, e.last_name, b.branch_name,
d.department_name, SUM(t.amount) AS total_transactions
FROM Employees e
JOIN Transactions t ON e.employee_id = t.employee_id
JOIN Branches b ON e.branch_id = b.branch_id
JOIN Departments d ON e.department_id = d.department_id
WHERE t.transaction_date >= CURDATE() - INTERVAL 6 MONTH
GROUP BY e.employee_id, e.first_name, e.last_name, b.branch_name,
d.department_name
HAVING total_transactions > 50000;

 List all accounts that have both a loan and a credit card associated with them,
including the account balance, loan amount, and credit limit.

sql
Copy code
SELECT a.account_id, a.account_number, a.balance, l.loan_amount,
cc.credit_limit
FROM Accounts a
JOIN Loans l ON a.customer_id = l.customer_id
JOIN CreditCards cc ON a.customer_id = cc.customer_id
WHERE a.account_id IN (
SELECT account_id
FROM Accounts
WHERE customer_id IN (SELECT customer_id FROM Loans)
AND customer_id IN (SELECT customer_id FROM CreditCards)
);
 Retrieve the investment details and the corresponding account manager's information
for investments made in the past year.

sql
Copy code
SELECT i.investment_id, i.investment_type, i.amount_invested,
i.investment_date, e.employee_id, e.first_name, e.last_name
FROM Investments i
JOIN Accounts a ON i.customer_id = a.customer_id
JOIN AccountManagers am ON a.account_id = am.account_id
JOIN Employees e ON am.employee_id = e.employee_id
WHERE i.investment_date >= CURDATE() - INTERVAL 1 YEAR;

 Find the total number of transactions and the total transaction amount for each
account type (savings/checking) in each branch.

sql
Copy code
SELECT b.branch_id, b.branch_name, a.account_type, COUNT(t.transaction_id)
AS transaction_count, SUM(t.amount) AS total_amount
FROM Branches b
JOIN Accounts a ON b.branch_id = a.branch_id
JOIN Transactions t ON a.account_id = t.account_id
GROUP BY b.branch_id, b.branch_name, a.account_type;

 List all customers who have made payments towards loans and also have at least one
active subscription to a bank service.

sql
Copy code
SELECT DISTINCT c.customer_id, c.first_name, c.last_name
FROM Customers c
JOIN Loans l ON c.customer_id = l.customer_id
JOIN Payments p ON l.loan_id = p.loan_id
JOIN ServicesSubscriptions ss ON c.customer_id = ss.customer_id;

 Retrieve the details of employees who manage accounts that have ATM transactions
totaling more than $10,000 in the past month.

sql
Copy code
SELECT e.employee_id, e.first_name, e.last_name, SUM(at.amount) AS
total_atm_transactions
FROM Employees e
JOIN AccountManagers am ON e.employee_id = am.employee_id
JOIN Accounts a ON am.account_id = a.account_id
JOIN ATMTransactions at ON a.account_id = at.account_id
WHERE at.transaction_date >= CURDATE() - INTERVAL 1 MONTH
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING total_atm_transactions > 10000;
 Find all customers who have both a savings account and a checking account, along
with the branch names and account balances.

sql
Copy code
SELECT c.customer_id, c.first_name, c.last_name, b.branch_name,
a.account_type, a.balance
FROM Customers c
JOIN Accounts a ON c.customer_id = a.customer_id
JOIN Branches b ON a.branch_id = b.branch_id
WHERE c.customer_id IN (
SELECT customer_id
FROM Accounts
WHERE account_type = 'Savings'
) AND c.customer_id IN (
SELECT customer_id
FROM Accounts
WHERE account_type = 'Checking'
);

 List the total number of loans and total loan amount issued by each branch, along
with the branch manager's details.

sql
Copy code
SELECT b.branch_id, b.branch_name, e.employee_id AS manager_id,
e.first_name AS manager_first_name, e.last_name AS manager_last_name,
COUNT(l.loan_id) AS total_loans, SUM(l.loan_amount) AS total_loan_amount
FROM Branches b
JOIN Employees e ON b.branch_id = e.branch_id AND e.department_id = (
SELECT department_id
FROM Departments
WHERE department_name = 'Management'
)
JOIN Loans l ON b.branch_id = l.branch_id
GROUP BY b.branch_id, b.branch_name, e.employee_id, e.first_name,
e.last_name;

 Retrieve the details of customers who have made more than 10 transactions in the last
month and have a total transaction amount exceeding $5000.

sql
Copy code
SELECT c.customer_id, c.first_name, c.last_name, COUNT(t.transaction_id) AS
transaction_count, SUM(t.amount) AS total_amount
FROM Customers c
JOIN Accounts a ON c.customer_id = a.customer_id
JOIN Transactions t ON a.account_id = t.account_id
WHERE t.transaction_date >= CURDATE() - INTERVAL 1 MONTH
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING transaction_count > 10 AND total_amount > 5000;
 Find the branches where more than 50% of the accounts have a balance below $1000,
including branch details and the percentage of such accounts.

sql
Copy code
SELECT b.branch_id, b.branch_name, COUNT(a.account_id) AS total_accounts,
SUM(CASE WHEN a.balance < 1000 THEN 1 ELSE 0 END) AS low_balance_accounts,
(SUM(CASE WHEN a.balance < 1000 THEN 1 ELSE 0 END) / COUNT(a.account_id)) *
100 AS percentage_low_balance
FROM Branches b
JOIN Accounts a ON b.branch_id = a.branch_id
GROUP BY b.branch_id, b.branch_name
HAVING percentage_low_balance > 50;

 Retrieve the loan details along with the associated customer's highest transaction
amount in the last year.

sql
Copy code
SELECT l.loan_id, l.loan_amount, l.issue_date, l.due_date, c.customer_id,
c.first_name, c.last_name, MAX(t.amount) AS highest_transaction
FROM Loans l
JOIN Customers c ON l.customer_id = c.customer_id
JOIN Accounts a ON c.customer_id = a.customer_id
JOIN Transactions t ON a.account_id = t.account_id
WHERE t.transaction_date >= CURDATE() - INTERVAL 1 YEAR
GROUP BY l.loan_id, l.loan_amount, l.issue_date, l.due_date, c.customer_id,
c.first_name, c.last_name;

 List the total credit limit for each customer who holds more than one credit card,
along with the customer's details.

sql
Copy code
SELECT c.customer_id, c.first_name, c.last_name, SUM(cc.credit_limit) AS
total_credit_limit
FROM Customers c
JOIN CreditCards cc ON c.customer_id = cc.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(cc.credit_card_id) > 1;

 Find all employees who work in multiple departments, including their branch and
department details.

sql
Copy code
SELECT e.employee_id, e.first_name, e.last_name, b.branch_name,
GROUP_CONCAT(DISTINCT d.department_name) AS departments
FROM Employees e
JOIN Branches b ON e.branch_id = b.branch_id
JOIN Departments d ON e.department_id = d.department_id
GROUP BY e.employee_id, e.first_name, e.last_name, b.branch_name
HAVING COUNT(DISTINCT d.department_id) > 1;
 Retrieve the list of customers who have made investments in more than three
different types of investments in the past two years.

sql
Copy code
SELECT c.customer_id, c.first_name, c.last_name, COUNT(DISTINCT
i.investment_type) AS investment_types
FROM Customers c
JOIN Investments i ON c.customer_id = i.customer_id
WHERE i.investment_date >= CURDATE() - INTERVAL 2 YEAR
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING investment_types > 3;

 List the branches where the total amount of ATM transactions in the last month
exceeds the total amount of in-branch transactions, including branch details.

sql
Copy code
SELECT b.branch_id, b.branch_name, SUM(at.amount) AS
total_atm_transactions, SUM(t.amount) AS total_in_branch_transactions
FROM Branches b
JOIN Accounts a ON b.branch_id = a.branch_id
JOIN ATMTransactions at ON a.account_id = at.account_id
JOIN Transactions t ON a.account_id = t.account_id
WHERE at.transaction_date >= CURDATE() - INTERVAL 1 MONTH AND
t.transaction_date >= CURDATE() - INTERVAL 1 MONTH
GROUP BY b.branch_id, b.branch_name
HAVING total_atm_transactions > total_in_branch_transactions;

 Find the customers who have made the highest number of payments towards loans in
the past six months, along with their loan and payment details.

sql
Copy code
SELECT c.customer_id, c.first_name, c.last_name, l.loan_id,
COUNT(p.payment_id) AS payment_count, SUM(p.payment_amount) AS
total_payments
FROM Customers c
JOIN Loans l ON c.customer_id = l.customer_id
JOIN Payments p ON l.loan_id = p.loan_id
WHERE p.payment_date >= CURDATE() - INTERVAL 6 MONTH
GROUP BY c.customer_id, c.first_name, c.last_name, l.loan_id
ORDER BY payment_count DESC
LIMIT 10;
 List all students enrolled in a specific course along with their grades.

sql
Copy code
SELECT s.student_id, s.student_name, e.grade
FROM STUDENTS s
JOIN ENROLLMENTS e ON s.student_id = e.student_id
WHERE e.course_id = 123; -- Replace 123 with the specific course_id

 Calculate the GPA of a student.

sql
Copy code
SELECT student_id, AVG(CASE
WHEN grade = 'A' THEN 4.0
WHEN grade = 'B' THEN 3.0
WHEN grade = 'C' THEN 2.0
WHEN grade = 'D' THEN 1.0
ELSE 0.0
END) AS gpa
FROM ENROLLMENTS
WHERE student_id = 456 -- Replace with student_id
GROUP BY student_id;

 Find courses with the highest enrollment.

sql
Copy code
SELECT course_id, COUNT(*) AS enrollment_count
FROM ENROLLMENTS
GROUP BY course_id
ORDER BY enrollment_count DESC
LIMIT 5; -- Adjust limit as needed

 Identify students who have not paid their fees.

sql
Copy code
SELECT s.student_id, s.student_name
FROM STUDENTS s
LEFT JOIN FEES f ON s.student_id = f.student_id
WHERE f.fee_id IS NULL;

 Calculate the total fees collected by department.

sql
Copy code
SELECT d.department_id, d.department_name, SUM(f.amount) AS total_fees
FROM DEPARTMENTS d
LEFT JOIN STUDENTS s ON d.department_id = s.department_id
LEFT JOIN FEES f ON s.student_id = f.student_id
GROUP BY d.department_id;

 Determine faculty teaching load (number of courses taught).

sql
Copy code
SELECT f.faculty_id, f.faculty_name, COUNT(*) AS courses_taught
FROM FACULTY f
JOIN COURSES c ON f.faculty_id = c.faculty_id
GROUP BY f.faculty_id;

 List all overdue library books.

sql
Copy code
SELECT lb.book_id, lb.book_title, ll.return_date
FROM LIBRARY_BOOKS lb
JOIN LIBRARY_LOANS ll ON lb.book_id = ll.book_id
WHERE ll.return_date < CURDATE();

 Find students with the highest average marks.


sql
Copy code
SELECT e.student_id, AVG(er.marks_obtained) AS avg_marks
FROM EXAM_RESULTS er
JOIN EXAMS e ON er.exam_id = e.exam_id
GROUP BY e.student_id
ORDER BY avg_marks DESC
LIMIT 10; -- Adjust limit as needed

 Calculate the late fee for overdue library books.

sql
Copy code
SELECT lb.book_id, lb.book_title, DATEDIFF(NOW(), ll.return_date) AS
days_overdue,
DATEDIFF(NOW(), ll.return_date) * late_fee_per_day AS late_fee
FROM LIBRARY_BOOKS lb
JOIN LIBRARY_LOANS ll ON lb.book_id = ll.book_id
WHERE ll.return_date < CURDATE();

 Identify courses without faculty assigned.

sql
Copy code
SELECT c.course_id, c.course_name
FROM COURSES c
LEFT JOIN FACULTY f ON c.faculty_id = f.faculty_id
WHERE f.faculty_id IS NULL;

 Calculate the total amount paid by each student.

sql
Copy code
SELECT s.student_id, s.student_name, SUM(p.amount) AS total_paid
FROM STUDENTS s
LEFT JOIN PAYMENTS p ON s.student_id = p.student_id
GROUP BY s.student_id;

 Identify courses where no students are enrolled.

sql
Copy code
SELECT c.course_id, c.course_name
FROM COURSES c
LEFT JOIN ENROLLMENTS e ON c.course_id = e.course_id
WHERE e.enrollment_id IS NULL;

 Calculate the average GPA for each department.

sql
Copy code
SELECT d.department_id, d.department_name, AVG(gpa) AS avg_gpa
FROM DEPARTMENTS d
JOIN STUDENTS s ON d.department_id = s.department_id
JOIN (
SELECT student_id, AVG(CASE
WHEN grade = 'A' THEN 4.0
WHEN grade = 'B' THEN 3.0
WHEN grade = 'C' THEN 2.0
WHEN grade = 'D' THEN 1.0
ELSE 0.0
END) AS gpa
FROM ENROLLMENTS
GROUP BY student_id
) AS student_gpa ON s.student_id = student_gpa.student_id
GROUP BY d.department_id;

 Find the busiest day in terms of library loans.

sql
Copy code
SELECT loan_date, COUNT(*) AS loans_count
FROM LIBRARY_LOANS
GROUP BY loan_date
ORDER BY loans_count DESC
LIMIT 1;

 Identify students who have borrowed the maximum number of books.

sql
Copy code
SELECT student_id, COUNT(*) AS books_borrowed
FROM LIBRARY_LOANS
GROUP BY student_id
ORDER BY books_borrowed DESC
LIMIT 5; -- Adjust limit as needed

 Calculate the pass percentage for each exam.

sql
Copy code
SELECT e.exam_id, e.course_id,
COUNT(CASE WHEN er.marks_obtained >= pass_marks THEN 1 END) /
COUNT(*) * 100 AS pass_percentage
FROM EXAMS e
JOIN EXAM_RESULTS er ON e.exam_id = er.exam_id
GROUP BY e.exam_id;

 List faculty members without assigned courses.

sql
Copy code
SELECT f.faculty_id, f.faculty_name
FROM FACULTY f
LEFT JOIN COURSES c ON f.faculty_id = c.faculty_id
WHERE c.course_id IS NULL;

 Find courses where average marks are below a certain threshold.

sql
Copy code
SELECT e.course_id, e.course_name,
AVG(er.marks_obtained) AS avg_marks
FROM EXAMS e
JOIN EXAM_RESULTS er ON e.exam_id = er.exam_id
GROUP BY e.course_id, e.course_name
HAVING AVG(er.marks_obtained) < 60; -- Adjust threshold as needed

 Identify students enrolled in multiple departments.

sql
Copy code
SELECT student_id, COUNT(DISTINCT department_id) AS enrolled_departments
FROM STUDENTS
GROUP BY student_id
HAVING enrolled_departments > 1;

 Calculate the total amount of fines collected for late fee payments.

sql
Copy code
SELECT SUM(late_fee) AS total_fines_collected
FROM (
SELECT DATEDIFF(NOW(), ll.return_date) * late_fee_per_day AS late_fee
FROM LIBRARY_LOANS ll
WHERE ll.return_date < CURDATE()
) AS late_fees;

1. List all students along with their enrolled courses and grades.

sql
Copy code
SELECT s.student_id, s.student_name, c.course_id, c.course_name,
e.grade
FROM STUDENTS s
LEFT JOIN ENROLLMENTS e ON s.student_id = e.student_id
LEFT JOIN COURSES c ON e.course_id = c.course_id;

2. Find faculty members teaching courses along with their department names.

sql
Copy code
SELECT f.faculty_id, f.faculty_name, d.department_name, c.course_id,
c.course_name
FROM FACULTY f
JOIN DEPARTMENTS d ON f.department_id = d.department_id
LEFT JOIN COURSES c ON f.faculty_id = c.faculty_id;

3. List students who have borrowed books from the library along with the book
details and loan dates.

sql
Copy code
SELECT s.student_id, s.student_name, lb.book_id, lb.book_title,
ll.loan_date
FROM STUDENTS s
JOIN LIBRARY_LOANS ll ON s.student_id = ll.student_id
JOIN LIBRARY_BOOKS lb ON ll.book_id = lb.book_id;
4. Calculate the total fees paid by each student along with their department names.

sql
Copy code
SELECT s.student_id, s.student_name, d.department_name, SUM(f.amount)
AS total_fees_paid
FROM STUDENTS s
JOIN DEPARTMENTS d ON s.department_id = d.department_id
LEFT JOIN FEES f ON s.student_id = f.student_id
GROUP BY s.student_id, s.student_name, d.department_name;

5. List courses along with their enrollment counts, faculty names, and department
names.

sql
Copy code
SELECT c.course_id, c.course_name, COUNT(e.enrollment_id) AS
enrollment_count,
f.faculty_name, d.department_name
FROM COURSES c
LEFT JOIN ENROLLMENTS e ON c.course_id = e.course_id
LEFT JOIN FACULTY f ON c.faculty_id = f.faculty_id
LEFT JOIN DEPARTMENTS d ON c.department_id = d.department_id
GROUP BY c.course_id, c.course_name, f.faculty_name,
d.department_name;

6. List all students along with their enrolled courses, grades, and faculty names.

sql
Copy code
SELECT s.student_id, s.student_name, c.course_id, c.course_name,
e.grade, f.faculty_name
FROM STUDENTS s
LEFT JOIN ENROLLMENTS e ON s.student_id = e.student_id
LEFT JOIN COURSES c ON e.course_id = c.course_id
LEFT JOIN FACULTY f ON c.faculty_id = f.faculty_id;

7. Find faculty members teaching courses along with the number of enrolled
students in each course.

sql
Copy code
SELECT f.faculty_id, f.faculty_name, c.course_id, c.course_name,
COUNT(e.enrollment_id) AS enrolled_students
FROM FACULTY f
JOIN COURSES c ON f.faculty_id = c.faculty_id
LEFT JOIN ENROLLMENTS e ON c.course_id = e.course_id
GROUP BY f.faculty_id, f.faculty_name, c.course_id, c.course_name;
8. List courses along with their average grades and department names.

sql
Copy code
SELECT c.course_id, c.course_name, AVG(CASE
WHEN e.grade = 'A' THEN 4.0
WHEN e.grade = 'B' THEN 3.0
WHEN e.grade = 'C' THEN 2.0
WHEN e.grade = 'D' THEN 1.0
ELSE 0.0
END) AS avg_grade,
d.department_name
FROM COURSES c
LEFT JOIN ENROLLMENTS e ON c.course_id = e.course_id
LEFT JOIN DEPARTMENTS d ON c.department_id = d.department_id
GROUP BY c.course_id, c.course_name, d.department_name;

9. Calculate the total fees paid by each student along with their course names and
department names.

sql
Copy code
SELECT s.student_id, s.student_name, c.course_name,
d.department_name, SUM(f.amount) AS total_fees_paid
FROM STUDENTS s
JOIN ENROLLMENTS e ON s.student_id = e.student_id
JOIN COURSES c ON e.course_id = c.course_id
JOIN DEPARTMENTS d ON c.department_id = d.department_id
LEFT JOIN FEES f ON s.student_id = f.student_id
GROUP BY s.student_id, s.student_name, c.course_name,
d.department_name;

10. List all courses along with their faculty names and the number of students who
have not yet enrolled.

sql
Copy code
SELECT c.course_id, c.course_name, f.faculty_name,
COUNT(s.student_id) AS not_enrolled_students
FROM COURSES c
LEFT JOIN FACULTY f ON c.faculty_id = f.faculty_id
LEFT JOIN ENROLLMENTS e ON c.course_id = e.course_id
LEFT JOIN STUDENTS s ON e.student_id = s.student_id
WHERE e.enrollment_id IS NULL
GROUP BY c.course_id, c.course_name, f.faculty_name;

11. Find students who have borrowed books along with the book details, loan dates,
and due dates.

sql
Copy code
SELECT s.student_id, s.student_name, lb.book_id, lb.book_title,
ll.loan_date, ll.return_date AS due_date
FROM STUDENTS s
JOIN LIBRARY_LOANS ll ON s.student_id = ll.student_id
JOIN LIBRARY_BOOKS lb ON ll.book_id = lb.book_id;
12. Calculate the pass percentage for each course in a specific semester.

sql
Copy code
SELECT c.course_id, c.course_name,
COUNT(CASE WHEN er.marks_obtained >= pass_marks THEN 1 END) /
COUNT(*) * 100 AS pass_percentage
FROM COURSES c
JOIN EXAMS e ON c.course_id = e.course_id
JOIN EXAM_RESULTS er ON e.exam_id = er.exam_id
WHERE e.semester = 'Spring 2024' -- Replace with specific semester
GROUP BY c.course_id, c.course_name;

13. List faculty members along with their department names and courses they are
teaching.

sql
Copy code
SELECT f.faculty_id, f.faculty_name, d.department_name, c.course_id,
c.course_name
FROM FACULTY f
JOIN DEPARTMENTS d ON f.department_id = d.department_id
LEFT JOIN COURSES c ON f.faculty_id = c.faculty_id;

14. Find courses with the highest average marks obtained in exams.

sql
Copy code
SELECT c.course_id, c.course_name, AVG(er.marks_obtained) AS
avg_marks
FROM COURSES c
JOIN EXAMS e ON c.course_id = e.course_id
JOIN EXAM_RESULTS er ON e.exam_id = er.exam_id
GROUP BY c.course_id, c.course_name
ORDER BY avg_marks DESC
LIMIT 5; -- Adjust limit as needed

15. List students along with the events they are scheduled to attend and event
details.

sql
Copy code
SELECT s.student_id, s.student_name, e.event_name, a.start_date,
a.end_date
FROM STUDENTS s
JOIN SERVICESUBSCRIPTIONS ss ON s.student_id = ss.customer_id
JOIN BANKSERVICES b ON ss.service_id = b.service_id
JOIN AGENCY a ON b.agency_id = a.agency_id
WHERE ss.subscription_date <= DATE '2022-07-13';
 List all users who have borrowed books along with their loan details and book titles.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, b.title, l.loan_date,
l.due_date, l.return_date
FROM USERS u
JOIN LOANS l ON u.user_id = l.user_id
JOIN BOOKS b ON l.book_id = b.book_id;

 Find the total number of books published by each publisher.

sql
Copy code
SELECT p.publisher_id, p.name, COUNT(b.book_id) AS total_books
FROM PUBLISHERS p
JOIN BOOKS b ON p.publisher_id = b.publisher_id
GROUP BY p.publisher_id, p.name;

 List all overdue books along with user details and fine amount.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, b.title, l.due_date, f.amount
FROM USERS u
JOIN LOANS l ON u.user_id = l.user_id
JOIN BOOKS b ON l.book_id = b.book_id
JOIN FINES f ON l.loan_id = f.loan_id
WHERE l.due_date < CURDATE() AND l.return_date IS NULL;
 Calculate the total fines collected per user.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, SUM(f.amount) AS total_fines
FROM USERS u
JOIN LOANS l ON u.user_id = l.user_id
JOIN FINES f ON l.loan_id = f.loan_id
GROUP BY u.user_id, u.first_name, u.last_name;

 Find the most popular books based on the number of loans.

sql
Copy code
SELECT b.book_id, b.title, COUNT(l.loan_id) AS loan_count
FROM BOOKS b
JOIN LOANS l ON b.book_id = l.book_id
GROUP BY b.book_id, b.title
ORDER BY loan_count DESC
LIMIT 10;

 List all reservations that have been canceled.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, b.title, r.reservation_date,
r.cancel_date
FROM USERS u
JOIN RESERVATIONS r ON u.user_id = r.user_id
JOIN BOOKS b ON r.book_id = b.book_id
WHERE r.cancel_date IS NOT NULL;

 Find the number of books in each genre.

sql
Copy code
SELECT g.genre_id, g.name, COUNT(bg.book_id) AS book_count
FROM GENRES g
JOIN BOOK_GENRES bg ON g.genre_id = bg.genre_id
GROUP BY g.genre_id, g.name;

 List all books along with their authors, publishers, and genres.

sql
Copy code
SELECT b.book_id, b.title, a.first_name AS author_first_name, a.last_name
AS author_last_name,
p.name AS publisher_name, g.name AS genre_name
FROM BOOKS b
JOIN AUTHORS a ON b.author_id = a.author_id
JOIN PUBLISHERS p ON b.publisher_id = p.publisher_id
JOIN BOOK_GENRES bg ON b.book_id = bg.book_id
JOIN GENRES g ON bg.genre_id = g.genre_id;

 Find users who have borrowed books from multiple branches.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, COUNT(DISTINCT bc.branch_id)
AS branches_count
FROM USERS u
JOIN LOANS l ON u.user_id = l.user_id
JOIN BOOK_COPIES bc ON l.book_id = bc.book_id
GROUP BY u.user_id, u.first_name, u.last_name
HAVING branches_count > 1;

 Calculate the average fine amount for overdue books.

sql
Copy code
SELECT AVG(f.amount) AS avg_fine_amount
FROM FINES f
JOIN LOANS l ON f.loan_id = l.loan_id
WHERE l.due_date < CURDATE() AND l.return_date IS NULL;

 List all books that are currently available in a specific branch.

sql
Copy code
SELECT bc.copy_id, b.title, bc.status
FROM BOOK_COPIES bc
JOIN BOOKS b ON bc.book_id = b.book_id
WHERE bc.branch_id = 1 AND bc.status = 'available'; -- Replace 1 with the
specific branch_id

 Find the total number of book copies in each branch.

sql
Copy code
SELECT lb.branch_id, lb.name, COUNT(bc.copy_id) AS total_copies
FROM LIBRARY_BRANCHES lb
JOIN BOOK_COPIES bc ON lb.branch_id = bc.branch_id
GROUP BY lb.branch_id, lb.name;

 List all authors along with the number of books they have written.

sql
Copy code
SELECT a.author_id, a.first_name, a.last_name, COUNT(b.book_id) AS
books_written
FROM AUTHORS a
JOIN BOOKS b ON a.author_id = b.author_id
GROUP BY a.author_id, a.first_name, a.last_name;

 Find users who have paid fines.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, SUM(p.amount) AS total_paid
FROM USERS u
JOIN LOANS l ON u.user_id = l.user_id
JOIN FINES f ON l.loan_id = f.loan_id
JOIN PAYMENTS p ON f.fine_id = p.fine_id
GROUP BY u.user_id, u.first_name, u.last_name;
 List all librarians along with the number of branches they manage.

sql
Copy code
SELECT l.librarian_id, l.first_name, l.last_name, COUNT(lb.branch_id) AS
branches_managed
FROM LIBRARIANS l
LEFT JOIN LIBRARY_BRANCHES lb ON l.librarian_id = lb.librarian_id
GROUP BY l.librarian_id, l.first_name, l.last_name;

 Find the total number of book copies for each book in all branches.

sql
Copy code
SELECT b.book_id, b.title, COUNT(bc.copy_id) AS total_copies
FROM BOOKS b
JOIN BOOK_COPIES bc ON b.book_id = bc.book_id
GROUP BY b.book_id, b.title;

 List books that have been reserved but not yet borrowed.

sql
Copy code
SELECT b.book_id, b.title, r.reservation_date
FROM BOOKS b
JOIN RESERVATIONS r ON b.book_id = r.book_id
LEFT JOIN LOANS l ON r.book_id = l.book_id AND r.user_id = l.user_id
WHERE l.loan_id IS NULL;

 Find the number of times each book has been borrowed.

sql
Copy code
SELECT b.book_id, b.title, COUNT(l.loan_id) AS borrow_count
FROM BOOKS b
JOIN LOANS l ON b.book_id = l.book_id
GROUP BY b.book_id, b.title;

 Calculate the total number of books reserved by each user.

sql
Copy code
SELECT u.user_id, u.first_name, u.last_name, COUNT(r.reservation_id) AS
total_reservations
FROM USERS u
JOIN RESERVATIONS r ON u.user_id = r.user_id
GROUP BY u.user_id, u.first_name, u.last_name;

 List all books along with their categories and the number of copies available in each
branch.

sql
Copy code
SELECT b.book_id, b.title, c.name AS category_name, lb.name AS branch_name,
COUNT(bc.copy_id) AS available_copies
FROM BOOKS b
JOIN BOOK_CATEGORIES bcg ON b.book_id = bcg.book_id
JOIN CATEGORIES c ON bcg.category_id = c.category_id
JOIN BOOK_COPIES bc ON b.book_id = bc.book_id
JOIN LIBRARY_BRANCHES lb ON bc.branch_id = lb.branch_id
WHERE bc.status = 'available'
GROUP BY b.book_id, b.title, c.name, lb.name;

1. Find members who have booked facilities and also attended events in the last six
months.

sql
Copy code
SELECT DISTINCT m.member_id, m.first_name, m.last_name
FROM MEMBER m
JOIN BOOKING b ON m.member_id = b.member_id
JOIN ATTENDANCE a ON m.member_id = a.member_id
WHERE b.booking_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
AND a.event_id IN (
SELECT event_id
FROM EVENT
WHERE event_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
);

2. List the households with the highest number of maintenance requests that are
still open, along with the facilities they have requested maintenance for.

sql
Copy code
SELECT h.household_id, h.owner_name, f.facility_name, COUNT(mr.request_id)
AS open_requests
FROM HOUSEHOLD h
JOIN MAINTENANCE_REQUEST mr ON h.household_id = mr.household_id
JOIN FACILITY f ON mr.facility_id = f.facility_id
WHERE mr.status = 'open'
GROUP BY h.household_id, h.owner_name, f.facility_name
ORDER BY open_requests DESC
LIMIT 5;

3. Retrieve the details of events that had the most attendees and were organized by
members from households with no overdue invoices.

sql
Copy code
SELECT e.event_id, e.event_name, e.event_date, e.location,
COUNT(a.member_id) AS attendees
FROM EVENT e
JOIN ATTENDANCE a ON e.event_id = a.event_id
JOIN MEMBER m ON e.organizer_id = m.member_id
JOIN HOUSEHOLD h ON m.household_id = h.household_id
WHERE h.household_id NOT IN (
SELECT household_id
FROM INVOICE
WHERE due_date < CURDATE() AND status = 'unpaid'
)
GROUP BY e.event_id, e.event_name, e.event_date, e.location
ORDER BY attendees DESC
LIMIT 3;

4. Find the total amount invoiced to each household, along with the total number of
events attended and facilities booked, for the current year.

sql
Copy code
SELECT h.household_id, h.owner_name,
COALESCE(SUM(i.amount), 0) AS total_invoiced,
COALESCE(COUNT(DISTINCT a.event_id), 0) AS total_events_attended,
COALESCE(COUNT(DISTINCT b.booking_id), 0) AS total_facilities_booked
FROM HOUSEHOLD h
LEFT JOIN INVOICE i ON h.household_id = i.household_id AND YEAR(i.due_date)
= YEAR(CURDATE())
LEFT JOIN MEMBER m ON h.household_id = m.household_id
LEFT JOIN ATTENDANCE a ON m.member_id = a.member_id AND YEAR(a.event_id) IN
(
SELECT event_id
FROM EVENT
WHERE YEAR(event_date) = YEAR(CURDATE())
)
LEFT JOIN BOOKING b ON m.member_id = b.member_id AND YEAR(b.booking_date) =
YEAR(CURDATE())
GROUP BY h.household_id, h.owner_name;

5. Retrieve the list of members who have not attended any event but have made
bookings for facilities.

sql
Copy code
SELECT DISTINCT m.member_id, m.first_name, m.last_name
FROM MEMBER m
LEFT JOIN ATTENDANCE a ON m.member_id = a.member_id
JOIN BOOKING b ON m.member_id = b.member_id
WHERE a.attendance_id IS NULL;

6. List the facilities that have had the most bookings, along with the details of the
members who booked them in the last three months.

sql
Copy code
SELECT f.facility_name, f.description, m.first_name, m.last_name,
b.booking_date, b.start_time, b.end_time
FROM FACILITY f
JOIN BOOKING b ON f.facility_id = b.facility_id
JOIN MEMBER m ON b.member_id = m.member_id
WHERE b.booking_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
ORDER BY f.facility_name, COUNT(b.booking_id) DESC;

7. Find the staff members who have managed the highest number of maintenance
requests, and list the facilities and households they have handled requests for.

sql
Copy code
SELECT s.staff_id, s.first_name, s.last_name, f.facility_name,
h.house_number, h.address, COUNT(mr.request_id) AS managed_requests
FROM STAFF s
JOIN MAINTENANCE_REQUEST mr ON s.staff_id = mr.staff_id
JOIN FACILITY f ON mr.facility_id = f.facility_id
JOIN HOUSEHOLD h ON mr.household_id = h.household_id
GROUP BY s.staff_id, s.first_name, s.last_name, f.facility_name,
h.house_number, h.address
ORDER BY managed_requests DESC
LIMIT 5;

8. List the top three most attended events and the members who attended them,
including their household information.

sql
Copy code
SELECT e.event_name, e.event_date, m.first_name, m.last_name,
h.house_number, h.address
FROM EVENT e
JOIN ATTENDANCE a ON e.event_id = a.event_id
JOIN MEMBER m ON a.member_id = m.member_id
JOIN HOUSEHOLD h ON m.household_id = h.household_id
WHERE e.event_id IN (
SELECT event_id
FROM ATTENDANCE
GROUP BY event_id
ORDER BY COUNT(member_id) DESC
LIMIT 3
)
ORDER BY e.event_name, e.event_date;

9. Retrieve the list of households that have vehicles manufactured after the year
2015 and have made maintenance requests in the last year.

sql
Copy code
SELECT DISTINCT h.household_id, h.owner_name, v.make, v.model, v.year
FROM HOUSEHOLD h
JOIN VEHICLE v ON h.household_id = v.household_id
JOIN MAINTENANCE_REQUEST mr ON h.household_id = mr.household_id
WHERE v.year > 2015 AND mr.request_date >= DATE_SUB(CURDATE(), INTERVAL 1
YEAR);

10. Find the members who have the highest number of different facility bookings
and list the details of the bookings they have made.

sql
Copy code
SELECT m.member_id, m.first_name, m.last_name, f.facility_name,
b.booking_date, b.start_time, b.end_time
FROM MEMBER m
JOIN BOOKING b ON m.member_id = b.member_id
JOIN FACILITY f ON b.facility_id = f.facility_id
WHERE m.member_id IN (
SELECT member_id
FROM BOOKING
GROUP BY member_id
ORDER BY COUNT(DISTINCT facility_id) DESC
LIMIT 5
)
ORDER BY m.first_name, m.last_name, b.booking_date;

You might also like