如何在sql中主表是tbl1时忽略来自tbl2的行?

时间:2011-02-22 06:44:36

标签: sql-server sql-server-2005

Visit
tmstamp,   trackno, qno, service
01/01/2011,1,       01,  Sv1
01/01/2011,2,       03,  Sv1
01/01/2011,3,       04,  Sv2
01/01/2011,4,       06,  Sv2
01/02/2011,1,       01,  Sv1

Matter
tmstamp,   trackno, code
01/01/2011,1,       a
01/01/2011,1,       b
01/01/2011,1,       e
01/01/2011,2,       c
01/01/2011,2,       b
01/01/2011,3,       c
01/01/2011,3,       a
01/01/2011,4,       d
01/01/2011,4,       c
01/02/2011,1,       a
01/02/2011,1,       b

select service, count(qno) as 'qno_served' from visit group by service

service, qno_served
SV1,     3
SV2,     2

我目前的陈述是每个qno有多少service

我想扭曲我的陈述,以便链接到matter表。并检查每个qno是否有code“a”。

如果qno有一个code“a”,我不想指望。

所以,我的最终结果将会结束。

service, qno_served
SV1,     1
SV2,     1

我应该使用join或wht方法来获取它吗?

2 个答案:

答案 0 :(得分:4)

尝试:

SELECT Service, COUNT(qno) AS [qno_served]
  FROM Visit
 WHERE NOT EXISTS (
    SELECT * FROM Matter WHERE Matter.TrackNo = Visit.TrackNo AND Matter.code = 'a')
 GROUP BY Service

答案 1 :(得分:1)

SELECT 
 V.service
,COUNT(1) AS qno_served

FROM MyDatabase.dbo.Visit AS V

LEFT JOIN (
    SELECT DISTINCT
    M.trackno

    FROM MyDatabase.dbo.Matter AS M

    WHERE M.code = 'a'
) AS T
    ON V.trackno = T.trackno

WHERE T.Trackno IS NULL

GROUP BY V.service

ORDER BY service