oracle 创建查询以选择打印机数量多于PC/笔记本电脑的制造商

k2fxgqgv  于 2023-03-01  发布在  Oracle
关注(0)|答案(2)|浏览(120)

大家好,我是SQL查询新手,我正在livesql.oracle中学习Oracle。我有这个数据库,我需要创建查询来选择制造打印机比pc\笔记本电脑多的制造商。制造商属性仅在Product表中,所有表共有的属性是model。表信息:

table Laptop (serial_number varchar(50),
 model,
 price,
 speed,
 ram,
 hd,
 screen,
 CONSTRAINT laptop_pk PRIMARY KEY (serial_number),
 CONSTRAINT laptop_2_product_fk
 FOREIGN KEY (model)
 REFERENCES Product(model)); 

table Product (model varchar(50),
 maker,
 type,
 CONSTRAINT product_pk PRIMARY KEY (model));

table Printer (serial_number varchar(50),
 model,
 price,
 color,
 type,
 CONSTRAINT printer_pk PRIMARY KEY (serial_number),
 CONSTRAINT printer_2_product_fk
 FOREIGN KEY (model)
 REFERENCES Product(model));

table PC (serial_number varchar(50),
 model,
 price,
 speed,
 ram,
 hd,
 cd,
 CONSTRAINT pc_pk PRIMARY KEY (serial_number),
 CONSTRAINT pc_2_product_fk
 FOREIGN KEY (model)
 REFERENCES Product(model));

table Storage (storage_id varchar(50),
 model,
 serial_number,
 transfered_to);

我所能做的就是选择做打印机而不是笔记本电脑的制造商。也许我应该为笔记本电脑的状况做一些类似的东西,看看哪些制造商生产更多的打印机。

SELECT DISTINCT maker
FROM Product
WHERE type = 'printer'
AND maker NOT IN (
    SELECT DISTINCT maker
    FROM Product
    WHERE type = 'laptop'
)
qltillow

qltillow1#

SELECT p.maker
FROM Product p
LEFT JOIN Printer pr ON p.model = pr.model
LEFT JOIN PC c ON p.model = c.model OR p.model = c.model
GROUP BY p.maker
HAVING COUNT(pr.serial_number) > COUNT(c.serial_number)

试试这个。在这里,我们使用LEFT JOIN将Product表与Printer和PC表联接起来,并使用COUNT函数计算每个制造商的打印机和PC/笔记本电脑的数量。然后,我们使用GROUP BY按制造商对结果进行分组,并使用HAVING子句对计数进行比较,以筛选出PC/笔记本电脑的产量多于打印机的制造商。

cnwbcb6i

cnwbcb6i2#

按照您的说法,“单独的”表是无关紧要的,因为您需要知道的一切都包含在product表中:它包含制造商以及 * 硬件 * 类型(无论是打印机、笔记本电脑还是其他任何东西)。
样本数据为:

SQL> select * from product order by type, maker, model;

MODEL       MAKER      TYPE
----------- ---------- -------
Dell LP 1   Dell       laptop
Dell LP 2   Dell       laptop
HP LP 1     HP         laptop
Dell PC 100 Dell       pc
HP PC 100   HP         pc
Dell PR 200 Dell       printer
Dell PR 201 Dell       printer
Dell PR 202 Dell       printer
Dell PR 203 Dell       printer
HP PR 300   HP         printer

10 rows selected.

查询使用条件聚合(在CTE中),而最终select返回打印机产量多于PC/笔记本电脑产量的制造商:

SQL> with temp as
  2    (select maker,
  3       sum(case when type = 'printer'         then 1 else 0 end) cnt_printer,
  4       sum(case when type in ('laptop', 'pc') then 1 else 0 end) cnt_laptop_pc
  5     from product
  6     group by maker
  7    )
  8  select *
  9  from temp
 10  where cnt_printer > cnt_laptop_pc;

MAKER      CNT_PRINTER CNT_LAPTOP_PC
---------- ----------- -------------
Dell                 4             3

SQL>

相关问题