简体   繁体   English

SQL示例查询解决方案(按技术和子查询技术分组)

[英]SQL Sample Query solutions (group by technique and the sub-query technique)

Tables: 表:

Classes(class, type, country, numGuns, Bore, displacement)
Ships(name, class, launched)

Question: Find for each class the year in the which the first ship of that class was launched? 问题:为每个班级查找该班级第一艘船的发射年份?

My Attempt: 我的尝试:

         select class, min(launched) from Ships
         group by (class)

Answer provided: 提供的答案:

         select class, launched from ships as s1
         where launched <= ALL (select year from ships as s2
                                where s2.class = s1.class)

So my question is, will I get desired result from my query? 所以我的问题是,查询会得到想要的结果吗? I don't really understand if it is as complicated as the Answer provided especially when there is no column as year in the table. 我真的不明白它是否像提供的答案那样复杂,尤其是当表中没有列作为年份时。

The minimum year in the group for class should correspond to the the first ship of that class. 该班级中的最小年份应对应于该班级的第一艘船。

Yes, your answer works. 是的,您的答案有效。

In fact it is better than the provided answer, because that query actually returns ALL ships and launches in a class, for the first year that that class was launched. 实际上,它比提供的答案要好,因为该查询实际上返回该类被启动的第一年的所有飞船并在一个类中启动。

Right solution to this problem. 正确解决此问题。

You're just selecting from Ships table but it's quite possible some classes do not have any ships assigned in Ships table, you need to consider those as well hence using a LEFT JOIN to adhere the condition. 您只是从Ships表中进行选择,但很有可能某些classesShips表中未分配任何船,因此您也需要考虑这些情况,因此请使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM