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方法来获取它吗?
答案 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