TASK: for each maker who has models at least in one of the tables PC, Laptop, or Printer, determine the maximum price for his products. Output: maker; if there are NULL values among the prices for the products of a given maker, display NULL for this maker, otherwise, the maximum price.
This is task 41 from this website: http://www.sql-ex.ru/
Database description:
The database scheme consists of four tables:
- Product (maker, model, type)
- PC (code, model, speed, ram, hd, cd, price)
- Laptop (code, model, speed, ram, hd, screen, price)
- Printer (code, model, color, type, price)
The Product
table contains data on the maker, model number, and type of product ('PC', 'Laptop', or 'Printer'). It is assumed that model numbers in the Product
table are unique for all makers and product types. Each personal computer in the PC table is unambiguously identified by a unique code, and is additionally characterized by its model (foreign key referring to the Product table), processor speed (in MHz) – speed field, RAM capacity (in Mb) - ram, hard disk drive capacity (in Gb) – hd, CD-ROM speed (e.g, '4x') - cd, and its price.
The Laptop
table is similar to the PC
table, except that instead of the CD-ROM speed, it contains the screen size (in inches) – screen. For each printer model in the Printer
table, its output type (‘y’ for color and ‘n’ for monochrome) – color field, printing technology ('Laser', 'Jet', or 'Matrix') – type, and price are specified.
I've tried several queries, most of them worked on the first database but not on the second one
Here's my last tried query:
SELECT DISTINCT
maker,
CASE
WHEN price IS NULL
THEN NULL
ELSE MAX(price) OVER (PARTITION by maker)
END max_p
FROM
(SELECT DISTINCT maker, price
FROM product
LEFT JOIN pc ON pc.model = product.model
WHERE product.model IN (SELECT model FROM pc)
UNION
SELECT DISTINCT maker, price
FROM product
LEFT JOIN laptop ON laptop.model = product.model
WHERE product.model IN (SELECT model FROM laptop)
UNION
SELECT DISTINCT maker, price FROM product
LEFT JOIN printer ON printer.model = product.model
WHERE product.model IN (SELECT model FROM printer)) as x
Your query returned the correct dataset on the first (available) database, but it returned incorrect dataset on the second checking database.