正在寻找解决此sql查询的更优雅的方法
我得到了一个具有 产品:正在寻找解决此sql查询的更优雅的方法,sql,Sql,我得到了一个具有 产品: maker model type 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 Pri
maker model type
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
这就是我想到的
select distinct maker, type
from Product
where maker in (select maker
from Product
group by maker, type
having count(model) > 1
except
select maker
from
(
select distinct maker, type
from Product
) A
group by maker
having count(type) > 1)
我知道这看起来并不优雅,所以我想知道是否有人能想出一个更好的选择,并解释为什么它比上面提到的查询更好
编辑:请确保答案仅为两栏宽,即
制造商,类型一种方法使用
存在
和不存在
:
select count(distinct model) as unique_model_count,
count(distinct type) as unique_type_count,
maker
from Product
group by maker
having unique_type_count=1 and unique_model_count>1
select distinct p.maker, p.type
from product p
where exists (select 1
from product p2
where p2.maker = p.maker and p2.type = p.type and p2.model <> p.model
) and
not exists (select 1
from product p2
where p2.maker = p.maker and p2.type <> p.type
);
你能为你的RDBMS引擎添加一个标签吗?子查询可以是一个GROUP BY,带有条件。这肯定是一个“正确”的答案!但是,我认为“制造商”和“类型”都需要包括在内;这里显示的内容的简单修复。(没有尝试过…)我不是100%确定列名是否可以如“Having”子句中所示使用,但可能必须在此处重复“count()”表达式。?逻辑正确,但如果未指定的RDBMS不允许having子句中使用别名,则可能引发错误。@MikeRobinson。我认为这不是正确的答案,因为它不包括
类型
。在大多数数据库中,这将返回一个错误(类型
未开始聚合)。在MySQL中,每个maker只返回一个类型
。我知道,但问题是哪个maker会生成一个类型,所以我认为它可以
select p.maker, p.type
from product p
where not exists (select 1
from product p2
where p2.maker = p.maker and p2.type <> p.type
)
group by p.maker, p.type
having min(model) <> max(model);
select p.model, p.type
from (select p.*,
min(type) over (partition by maker) as mintype,
max(type) over (partition by maker) as maxtype,
row_number() over (partition by maker, type order by model) as seqnum,
count(*) over (partition by maker, type) as cnt
from product p
) p
where seqnum = 1 and
mintype = maxtype and
cnt > 1;
SELECT maker, MIN(type) as type
FROM Product
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1 AND COUNT(DISTINCT model) > 1;