0

架构如下:

船舶(名称、发射年份、国家、数量、枪大小、排水量)

战斗(船,战名,结果)

其中名称和船是相等的。我的意思是如果“密苏里”是名称的元组结果之一,“密苏里”也将作为船舶的元组结果出现。

(即名称='密苏里',船='密苏里)他们是一样的

现在我的问题是我会做什么样的 SQL 语句来列出拥有最多枪支的战列舰列表中的战列舰(即 gunSize)

我试过了:

SELECT name, max(gunSize)
FROM Ships

但这给了我错误的结果。

然后我尝试了:

SELECT s.name
FROM Ships s,
   (SELECT MAX(gunSize) as "Largest # of Guns"
   FROM Ships
   GROUP BY name) maxGuns
WHERE s.name = maxGuns.name

但是后来 SQLite 管理员给了我一个错误,说即使我将它指定为别名,也不存在这样的列“maxGuns”:maxGuns

你们有谁知道这个问题的正确查询是什么?谢谢!

4

3 回答 3

0

您查询中的问题是子查询没有名为 的列name

无论如何,要找到最大数量的枪支,只需使用SELECT MAX(gunSize) FROM Ships. 要获得具有该数量枪支的所有船舶,您只需与该值进行简单比较:

SELECT name
FROM Ships
WHERE gunSize = (SELECT MAX(gunSize)
                 FROM Ships)
于 2013-10-23T09:12:39.263 回答
0

它不存在,因为您试图在“Where”子句中为子查询设置别名,而不是为表中的特定列设置别名。为了识别拥有最多枪支的船,您可以尝试以下操作:

    with cte as (select *
   ,ROW_NUMBER()  over (order by s.gunsize desc) seq
    from ships s )

    select * from cte 
    where seq = '1'

另一种方法可能是:它只会选择第一排,包含枪支数量最多的船。

     select Top 1 *
     from ships s 
     order by s.gunsize desc
于 2013-10-23T09:19:30.993 回答
-2
WITH TAB_SHIPS(NAME, NUMGUNS,DISPLACEMENT) AS (SELECT NAME, NUMGUNS,DISPLACEMENT FROM SHIPS AS S
LEFT JOIN CLASSES AS C
ON S.CLASS=C.CLASS
WHERE C.NUMGUNS >=ALL(SELECT NUMGUNS FROM CLASSES C1 WHERE C1.DISPLACEMENT = C.DISPLACEMENT ) 
UNION
SELECT SHIP, NUMGUNS,DISPLACEMENT FROM OUTCOMES AS O
LEFT JOIN CLASSES AS C
ON C.CLASS=O.SHIP
WHERE C.NUMGUNS >=ALL(SELECT NUMGUNS FROM CLASSES C1 WHERE C1.DISPLACEMENT = C.DISPLACEMENT ) )

SELECT NAME FROM TAB_SHIPS
WHERE NUMGUNS IS NOT NULL 
于 2015-08-01T19:41:39.390 回答