表:
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)所以我的问题是,我能从我的查询中得到想要的结果吗?我真的不明白它是否像提供的答案一样复杂,特别是在表中没有year列的情况下。
班级分组中的最小年份应对应于该班级的第一艘船。
发布于 2013-03-11 02:12:36
是的,你的答案是有效的。
实际上,它比提供的答案更好,因为该查询实际上返回了某个类中的所有船舶和下水,这是该类推出的第一年。
发布于 2017-10-13 13:42:05
这个问题的正确解决方案。
您只是从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;发布于 2019-10-13 20:22:01
select c.class , min (launched)
from classes c left join ships s on c.class = s.class
group by c.class
;https://stackoverflow.com/questions/15325574
复制相似问题