Noob关注:T-SQL嵌套子查询

时间:2012-10-31 02:46:12

标签: sql tsql

我有一张名为诺贝尔的桌子,其中包括以下字段:年,主题和获胜者。

此表代表多年来在各种科目中获奖的诺贝尔奖获得者。

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

我认为答案看起来如下:

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

我很确定我的语法错了......而且我不确定我是不是走正确的道路。帮助将不胜感激。谢谢!

5 个答案:

答案 0 :(得分:3)

试试这个:

SELECT yr 
FROM nobel n1 
WHERE n1.subject = 'Physics'
AND yr NOT IN (SELECT yr FROM nobel WHERE subject = 'Chemistry')

答案 1 :(得分:1)

除非您使用的是SQL Server 2000,否则EXCEPT适用于2005 +。

    SELECT yr
      FROM nobel 
     WHERE subject = 'Chemistry'
EXCEPT
    SELECT yr
      FROM nobel
     WHERE subject = 'Physics'

答案 2 :(得分: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
            )

答案 3 :(得分:0)

我认为你可能会走错路。你所拥有的where子句基本上是说'化学'='物理',它永远不会成真。

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

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

答案 4 :(得分: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