如何将带有条件的SQL计数作为子查询包含在内

时间:2013-11-17 08:23:01

标签: sql debugging subquery aggregate-functions

我写过这个问题:

select a_patient.pID,
       pname,
       ( select count(*)
           from app
          where staffID = 1234
            and app.staffID = a_patient.staffID
       )
  from app,
       a_patient
 where app.pID = a_patient.pID 
 order
    by surname
;

问题是,子查询返回所有记录的计数,而不是那些staffID = 1234的记录的计数。

我哪里错了?

1 个答案:

答案 0 :(得分:0)

使用count中的主键而不是通配符,并将子查询移动到WHERE子句,如下例所示:

SELECT U.Id as [User Link], U.Reputation
FROM Users U
WHERE
(SELECT Count(V.Id) AS [FAVORITES] FROM Votes V, VoteTypes Vt WHERE Vt.Id = V.VoteTypeId AND U.Id = V.UserId AND Vt.Id = 5) > 1000
ORDER BY U.Reputation DESC

<强>参考