SQL group by和having子句问题wrt计数

时间:2016-10-04 11:06:30

标签: sql

我有一张下表产品 制造商型号

A      1232  PC
A      1233  PC 
A      1276  Printer
A      1298  Laptop
A      1401  Printer
A      1408  Printer
A      1752  Laptop
B      1121   PC 
B      1750  Laptop
C      1321  Laptop
D      1288  Printer
D      1433  Printer
E      1260  PC
E      1434  Printer
E      2112  PC
E      2113  PC

我想找出只生产一种产品类型和多种型号的制造商。

答案是

Maker Type
D        Printer

到目前为止,我已经写了这个查询:

Select maker, type 
from product  
group by type, maker 
having count(model) > 1    

它给出了以下结果:

制造商类型

A     Laptop
A     PC
A     Printer
D     Printer
E     PC

我的问题是如何写条件才能获得1种类型的结果?因为写入有计数(类型)= 1删除了所需的制造商D.

3 个答案:

答案 0 :(得分:1)

这个怎么样?

Select maker, max(type) as type
from product  
group by maker 
having min(type) = max(type) and
       min(model) <> max(model);

答案 1 :(得分:0)

这个怎么样:

SELECT DISTINCT p1.Maker, p1.[Type]
FROM product p1
JOIN 
(
  Select maker
  from product  
  group by maker 
  having count(distinct model) > 1    
  AND count(distinct [type]) = 1
) p2
ON p1.MAKER = p2.MAKER

或者:

SELECT DISTINCT p1.Maker, p1.[Type]
FROM product p1
WHERE maker in
(
  Select maker
  from product  
  group by maker 
  having count(distinct model) > 1    
  AND count(distinct [type]) = 1
)

答案 2 :(得分:0)

SELECT distinct maker, type from product 
group by maker having count(distinct model)>1 AND 
count(distinct type) = 1;