[英]SQL Sample Query solutions (group by technique and the sub-query technique)
表:
Classes(class, type, country, numGuns, Bore, displacement)
Ships(name, class, launched)
问题:为每个班级查找该班级第一艘船的发射年份?
我的尝试:
select class, min(launched) from Ships
group by (class)
提供的答案:
select class, launched from ships as s1
where launched <= ALL (select year from ships as s2
where s2.class = s1.class)
所以我的问题是,查询会得到想要的结果吗? 我真的不明白它是否像提供的答案那样复杂,尤其是当表中没有列作为年份时。
该班级中的最小年份应对应于该班级的第一艘船。
是的,您的答案有效。
实际上,它比提供的答案要好,因为该查询实际上返回该类被启动的第一年的所有飞船并在一个类中启动。
正确解决此问题。
您只是从Ships
表中进行选择,但很有可能某些classes
在Ships
表中未分配任何船,因此您也需要考虑这些情况,因此请使用LEFT JOIN
遵守条件。
SELECT C.class,
CASE WHEN S.launched IS NULL THEN
(SELECT MIN(launched)
FROM Ships as S
WHERE S.class = C.class) ELSE S.launched END
FROM Classes as C LEFT JOIN Ships as S
ON C.class = S.name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.