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

如何将带有条件的SQL计数包含为子查询,sql,debugging,subquery,aggregate-functions,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

我写了这个查询:

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
的记录的计数


哪里出错了?

在计数中使用主键而不是通配符,并将子查询移动到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
参考资料


您使用的是哪种dbms?我认为您必须使用正确的别名,但不应该这样做。事实上,此查询应返回所有应用程序/患者组合,并返回
0
,作为除1234以外的所有员工的计数。你能确认吗?嗨,阿米莉莎,我用的是OracleHi Alexander,是的,我想我用的是正确的别名,但也许我应该在计数部分去掉交叉引用,只包括标记标准?因为正如Golez正确地指出的那样,计数返回为零。