SQL Find products that satisfy BOTH conditions below: (a) Its unit price must NO
ID: 3880123 • Letter: S
Question
SQL
Find products that satisfy BOTH conditions below:
(a) Its unit price must NOT below $22.
(b) Its category ID is 4 or 7 or 8. If its category ID is 1 or 3, then it must
have at least 40 units in stock.
Display their ProductID, UnitPrice, CategoryID, and UnitsInStock. The output should
be sorted by CategoryID in A -> Z order (i.e., from smallest to largest). For those
with the same CategoryID, the one with the highest UnitPrice should be displayed first.
Hint 1: a compound condition with AND, OR, NOT.
Hint 2: correct output has 16 products.
Part 2:
For products that meet both (a) and (b) conditions of previous Query, if we rank them in Z -> A
order of ProductID, i.e., from largest to smallest and the one with the largest ProductID
will be ranked as #1. Based on this rank, find only four of them which are ranked #8, #9,
#10 and #11. The output should contains same four columns as in previous Query.
Hint: extend ORDER BY with OFFSET.
Tables: Products, Categories, Suppliers
Explanation / Answer
Hi,
As you hae not shared the complete table structure of tables Products, Categories, Suppliers, and also the primary and foreign key relationships among them. I assume that we have the supplierID and CategoryID column in Products table which can be used to join the tables.
Ans 1 a) Select ProductID, UnitPrice, CategoryID, UnitsInStock from Products p join categories c on p.categoryID= c.categoryID join Suppliers s on p.supplierID=s.supplierID where UnitPrice!=22
order by CategoryID asc,UnitPrice desc;
Ans 1 b)Select ProductID, UnitPrice, CategoryID, UnitsInStock from Products p join categories c on p.categoryID= c.categoryID join Suppliers s on p.supplierID=s.supplierID where CategoryID in('4','7','8') or ( CategoryID in('1','3') and UnitsInStock>=40) order by CategoryID asc,UnitPrice desc;
Ans 2- Below query satisfies conditions given in part A and B
Select ProductID, UnitPrice, CategoryID, UnitsInStock from Products p join categories c on p.categoryID= c.categoryID join Suppliers s on p.supplierID=s.supplierID where CategoryID in('4','7','8') or ( CategoryID in('1','3') and UnitsInStock>=40) and UnitPrice!=22 order by ProductID desc OFFSET 7 ROWS FETCH NEXT 4 ROWS ONLY;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.