Sql 使用count()和group by时出现问题
我有一个名为Products的表,看起来像:Sql 使用count()和group by时出现问题,sql,count,group-by,Sql,Count,Group By,我有一个名为Products的表,看起来像: maker model type ---------- ------- ----- A 1232 PC A 1233 PC A 1276 Printer A 1401 Printer A 1408 Printer A 1298 Laptop A 175
maker model type
---------- ------- -----
A 1232 PC
A 1233 PC
A 1276 Printer
A 1401 Printer
A 1408 Printer
A 1298 Laptop
A 1752 Laptop
B 1121 PC
B 1750 Laptop
C 1321 Laptop
D 1433 Printer
D 1288 Printer
E 1260 PC
E 1434 Printer
E 2112 PC
E 2113 PC
我需要找一个生产不止一个型号的制造商,但那个型号应该是同一型号的。。。这里应该是maker=D,Type=Printer
我花了一整天的时间使用countmodel>1和counttype=1等。没有任何效果。如果您想确定具有多个相同类型模型的制造商,则可以使用GROUP BY并获得结果:
SELECT maker,
MIN(type) AS type
FROM Products
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1
AND COUNT(DISTINCT model) >1
select maker
from products
group by maker
having count(distinct model) > 1 -- more than one model
and count(distinct type) = 1 -- same type
查看是否要返回每个制造商的所有内容,然后使用即可使用
select p.maker, p.model, p.type
from products p
where maker in (select maker
from products t
group by maker
having count(distinct model) > 1
and count(distinct type) = 1);
请参见如果要确定具有多个相同类型模型的制造商,则可以使用GROUP BY并获得结果:
select maker
from products
group by maker
having count(distinct model) > 1 -- more than one model
and count(distinct type) = 1 -- same type
查看是否要返回每个制造商的所有内容,然后使用即可使用
select p.maker, p.model, p.type
from products p
where maker in (select maker
from products t
group by maker
having count(distinct model) > 1
and count(distinct type) = 1);
看你能列出一个想要的输出吗?我写的。它应该是“D”制造器和“打印机”类型。你能设计出想要的输出吗?我写的。它应该是“D”制造商和“打印机”类型的上帝,我已经在不同的地方跳舞很多次了facepalm:DD谢谢!你能解释一下MINtype在这里做什么吗?我不想按它分组,因为我想在它上面有一个agragate函数。因此,如果我仍然想显示它,那么我必须将它添加到那里。我可以用MAX…意思是它从两个相同的值中选择?打印机和打印机?天哪,我已经在不同的地方跳了很多次了facepalm:DD,谢谢!你能解释一下MINtype在这里做什么吗?我不想按它分组,因为我想在它上面有一个agragate函数。因此,如果我仍然想显示它,那么我必须将它添加到那里。我可以用MAX…意思是它从两个相同的值中选择?打印机和打印机?它不会返回所需的值。。。请看接受的答案。@Daria,误解了你原来的问题,虽然接受的答案可能更好,但现在应该可以了。它没有返回所需的值。。。请看被接受的答案。@Daria,误解了你原来的问题,虽然被接受的答案可能更好,但现在应该可以了。谢谢。第二个更好。我会接受你的回答,但吉安尼斯·帕拉斯凯沃普洛斯先回答了。非常感谢。第二个更好。我会接受你的回答,但Giannis Paraskevopoulos首先回答。你应该在回答时以正确的方式格式化你的代码。你应该在回答时以正确的方式格式化你的代码。