在识别我的错误时遇到问题

时间:2013-10-25 00:20:50

标签: sql select

已创建且不可修改的表是Book和Author。

预订(标题,价格,Yeareleased)

作者(AName, BTITLE,位置

Italized是关键 作者中的Btitle是引用Book(Title)的外键。

我的SQL查询:

   select distinct AName
   from Author
   where position in (2,3) AND position<>1
   group by AName

当我执行此操作时,我得到了所有在第2或第3位都有一本书的作者。这就是我想要的但我只是想让那些在所有书中都有2或3位的作者。 基本上归功于所有书中排名第二或第三的每位作者。

5 个答案:

答案 0 :(得分:1)

也许这样的事情会起作用:

select distinct AName
from @Author
where position in (2,3) 
except 
select distinct AName
from @Author
where position not in (2,3) 

它使一组那些位于第2和第3位的作者然后删除那些有另一个位置的作者。

答案 1 :(得分:1)

目前尚不完全清楚是否有人共同编写了2本书,并且在第二项和第三项中排在第二位。允许它更简单;如果您需要更严格的条件,可以优化查询。

回答这个问题的一种方法是让关键的观察结果表明你对作者所感兴趣的作品,他们所写的书籍数量等于他们被列为第二或第三作者的书籍数量。

进行一些TDQD - 测试驱动的查询设计

每位作者写的书数

SELECT Aname, COUNT(*) AS BookCount
  FROM Author
 GROUP BY AName

每位作者写作第二或第三作者的书籍数量

SELECT Aname, COUNT(*) AS NonLeadAuthorCount
  FROM Author
 WHERE Position IN (2, 3)
 GROUP BY Aname

加入计数相同的两个

SELECT X.Aname
  FROM (SELECT Aname, COUNT(*) AS BookCount
          FROM Author
         GROUP BY AName
       ) AS X
  JOIN (SELECT Aname, COUNT(*) AS NonLeadAuthorCount
          FROM Author
         WHERE Position IN (2, 3)
         GROUP BY Aname
       ) AS Y
    ON X.BookCount = Y.NonLeadAuthorCount

另一种看待的方式是'在第2或第3位写了一本书的集合作者减去写了一本既不是2也不是3'的书的作者集。为此,请参阅answer jpw

答案 2 :(得分:1)

尝试编写标准SQL:

SELECT AName FROM (
   SELECT 
      AName, 
      COUNT(*) AS count_all,
      (SELECT COUNT(*) FROM Author AS aa WHERE aa.AName = a.AName AND position=2) AS count_2,
      (SELECT COUNT(*) FROM Author AS aa WHERE aa.AName = a.AName AND position=3) AS count_3,
   FROM Author AS a
   GROUP BY AName
) AS t
WHERE count_all = count_2
OR count_all = count_3

我希望这对你有用。

答案 3 :(得分:0)

试试这个:

select AName from Author where position=2 OR position=3 group by AName;

答案 4 :(得分:0)

尝试添加

and AName not in (select AName from Author where position != 2 and position != 3

或类似的......