在情况下从表中选择

时间:2014-04-21 15:48:39

标签: sql select

有制造商,型号和类型的表。我应该选择所有拥有1个以上型号的制造商,但所有制造商的型号都相同 我的尝试是

select maker, type
from product
where 
((select count(model) from product) = (select count(model) from product where type='Printer')) or
((select count(model) from product) = (select count(model) from product where type='PC')) or
((select count(model) from product) = (select count(model) from product where type='Laptop'))

但它没有给出正确的答案。有人可以帮助我吗?

P.S。类型只能是打印机,PC或笔记本电脑

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT maker 
FROM PRODUCT
GROUP BY type, maker
HAVING COUNT(model)>1;

此外,这是sql小提琴文件http://sqlfiddle.com/#!4/5f09a/1

答案 1 :(得分:1)

以下查询可能会为您提供所需的结果:

SELECT DISTINCT product.maker, product.type
FROM product
INNER JOIN
(SELECT maker, count(distinct model) model_count, count(distinct type) type_count
FROM product
GROUP BY maker
HAVING count(distinct model) > 1
AND count(distinct type) = 1
) selected_makers
ON product.maker = selected_makers.maker
ORDER BY product.maker;

内联视图selected_makers首先选择具有多个模型但只有一种类型的制造商。然后,这些制造商的详细信息可从products表中获得。

答案 2 :(得分:0)

然后我想这就是你想要的。只有1种类型,但有多种型号的制造商:

SELECT maker FROM product
GROUP BY maker
HAVING COUNT(*) > 1
AND COUNT(DISTINCT type) == 1;