SQL 查询解决方案的有效总结
An Efficient Summarisation of this SQL Query Solution
我从 SQL-EX.RU
得到了这个 SQL 查询练习
Find out makers who produce only the models of the same type, and the
number of those models exceeds 1. Deduce: maker, type
Table 信息:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price) Printer(code,
model, color, type, price)
我写的版本(先在我的jotta pad上刮了一下lolz):
SELECT Product.maker, Product.type
FROM Product
WHERE Product.maker IN
(SELECT X.maker
FROM
(SELECT DISTINCT maker,type
FROM Product
) AS X
GROUP BY X.maker
HAVING COUNT(X.type) = 1
)
GROUP BY Product.maker,Product.type
HAVING COUNT(Product.model) > 1
这给了我正确的结果。但是,我相信这可能不是唯一的解决方案(至少不是理想的解决方案)- 因为我不是 SQL 向导。
我将不胜感激任何对答案的解释,但如果我能更好地简化它,我会用新的查询语句更新问题。
Ta
更新
自从最初的帖子我总结为:
SELECT maker, type
FROM Product
WHERE Product.maker IN
(
SELECT maker
FROM Product
GROUP BY maker
HAVING COUNT(DISTINCT type)=1
)
GROUP BY maker, type
HAVING COUNT(product.model) > 1
可以简化为:
SELECT maker ,
MAX(type) AS type
FROM product
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1
AND COUNT(*) > 1
此处您按制造商对结果进行分组,并且您只需要那些不同类型计数为 1 且组中总行数大于 1 的组。
你可以这样写:
HAVING COUNT(DISTINCT type) = 1
AND COUNT(DISTINCT model) > 1
但是和It is assumed that model numbers in the Product table are unique for all the makers and product types
一样。
我从 SQL-EX.RU
得到了这个 SQL 查询练习Find out makers who produce only the models of the same type, and the number of those models exceeds 1. Deduce: maker, type
Table 信息:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price) Printer(code, model, color, type, price)
我写的版本(先在我的jotta pad上刮了一下lolz):
SELECT Product.maker, Product.type
FROM Product
WHERE Product.maker IN
(SELECT X.maker
FROM
(SELECT DISTINCT maker,type
FROM Product
) AS X
GROUP BY X.maker
HAVING COUNT(X.type) = 1
)
GROUP BY Product.maker,Product.type
HAVING COUNT(Product.model) > 1
这给了我正确的结果。但是,我相信这可能不是唯一的解决方案(至少不是理想的解决方案)- 因为我不是 SQL 向导。
我将不胜感激任何对答案的解释,但如果我能更好地简化它,我会用新的查询语句更新问题。
Ta
更新 自从最初的帖子我总结为:
SELECT maker, type
FROM Product
WHERE Product.maker IN
(
SELECT maker
FROM Product
GROUP BY maker
HAVING COUNT(DISTINCT type)=1
)
GROUP BY maker, type
HAVING COUNT(product.model) > 1
可以简化为:
SELECT maker ,
MAX(type) AS type
FROM product
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1
AND COUNT(*) > 1
此处您按制造商对结果进行分组,并且您只需要那些不同类型计数为 1 且组中总行数大于 1 的组。
你可以这样写:
HAVING COUNT(DISTINCT type) = 1
AND COUNT(DISTINCT model) > 1
但是和It is assumed that model numbers in the Product table are unique for all the makers and product types
一样。