如何进行困难的GROUP查询以获取2组信息

时间:2013-01-14 17:30:39

标签: sql

有下表:

Product(maker, model, type)

制造商 - 设备制造商,类型是PC,笔记本电脑,打印机,型号是主键。我需要让所有制造商只生产相同类型的设备并制造超过1种型号。显示的信息是制造商,类型。我有以下问题:

SELECT maker, type, count(*) as how_many 
FROM Product 
GROUP BY maker, type 
HAVING count(*) > 1

但我不知道如何让制造商使用相同类型的设备。

更新:例如,有以下记录:

A - 01 - Printer
A - 02 - PC
A - 03 - Laptop
B - 04 - Printer
B - 05 - Printer

B是好的制造商,因为他的所有设备都有相同的类型 - “打印机”。我修好了你吗?

2 个答案:

答案 0 :(得分:1)

我认为这会给你想要的结果:

select maker, type, count(*) how_many
from product p1
group by maker, type
having how_many = (select count(type)
                   from product p2
                   where p1.maker = p2.maker
                   group by maker)

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

这是一个带有having子句的简单聚合查询:

select maker
from product
group by maker
having count(distinct type) = 1 and count(distinct type) > 1
相关问题