1

我有一个名为 nobel 的表,其中包含以下字段:年、主题和获胜者。

这张表代表了多年来在各种学科中的诺贝尔奖获得者。

我正在寻找获得物理奖但没有获得化学奖的年份。

我在想答案看起来像下面这样:

SELECT yr FROM nobel 
WHERE subject ('Chemistry') IN (SELECT subject FROM nobel WHERE subject = 'Physics')

我相当确定我的语法错误......而且我不确定我是否走在正确的道路上。帮助将不胜感激。谢谢!

4

5 回答 5

3

试试这个:

SELECT yr 
FROM nobel n1 
WHERE n1.subject = 'Physics'
AND yr NOT IN (SELECT yr FROM nobel WHERE subject = 'Chemistry')
于 2012-10-31T02:52:17.800 回答
1

除非您使用的是 SQL Server 2000,否则EXCEPT可以在 2005+ 上运行。

    SELECT yr
      FROM nobel 
     WHERE subject = 'Chemistry'
EXCEPT
    SELECT yr
      FROM nobel
     WHERE subject = 'Physics'
于 2012-10-31T03:00:36.027 回答
1

下面的代码将为您提供所需的结果。

 SELECT n1.yr
    FROM nobel n1
    WHERE subject = 'physics'
        AND NOT EXISTS (
            SELECT yr
            FROM nobel n2
            WHERE subject = 'chemistry' AND n2.yr = n1.yr
            )
于 2012-10-31T07:12:47.390 回答
0

我想你可能走错了路。您拥有的 where 子句本质上是在说 where 'Chemistry' = 'Physics' 这永远不会是真的。

我认为你需要做的是找出物理和化学的获奖年份,然后找到只有物理获奖的年份。

SELECT yr
FROM Nobel
LEFT JOIN
(
  SELECT SUM(1), yr
  FROM  Nobel
  WHERE subject = 'Chemistry'
  Group By yr
) as Chemistry
ON Chemistry.yr = Nobel.Yr
LEFT JOIN
(
  SELECT SUM(1), yr
  FROM  Nobel
  WHERE subject = 'Physics'
  Group By yr
) as Physics
ON Physics.yr = Nobel.yr

WHERE Physics.YR IS NOT NULL AND Chemistry.Yr IS NULL

GROUP BY yr
于 2012-10-31T02:52:14.133 回答
0

我们可以做两个派生表并将它们连接起来。

SELECT c.Year FROM 
c (SELECT Year, COUNT(*) FROM nobel where subject = 'chem' GROUP By Year) INNER JOIN
p (SELECT Year, COUNT(*) FROM nobel where subject = 'phy' GROUP By Year) ON c.Year = p.Year
WHERE c.Count != 0 and p.Count = 0
于 2012-10-31T02:52:40.323 回答