2

So here is what I am trying to accomplish. I have a single table, transactions, that has multiple entries of a sessionId with transactionCodes. I am trying to count distinct SessionId's only if they do not contain a specific transCode.

So basically transactions could look like:

sessionId    transcode
1            100
1            101
1            102
2            100
2            101
2            102
2            103

What I need to do is along these lines.

select count(distinct sessionId) where transCode != 103;

I would expect the above to only return a single record but in practice it obviously does not because my novice level SQL query returns me far more records than it should!

4

2 回答 2

3

有几种方法可以处理它。也许最简单的方法是通过NOT IN ()子查询:

SELECT
  COUNT(DISTINCT sessionId) 
FROM transcode
WHERE
  sessionId NOT IN (SELECT sessionId FROM transcode WHERE transcode = 103)

示例:http ://sqlfiddle.com/#!2/14bda/3

也可以通过右侧桌子上的LEFT JOIN查找来完成。NULL这可能比NOT IN ()在较大的表上更有效。

SELECT
  COUNT(DISTINCT t.sessionId)
FROM
  transcode t
  /* LEFT JOIN against a subquery returning only sessionId with a 103 transcode */
  LEFT JOIN (
    SELECT sessionId FROM transcode WHERE transcode = 103
  ) texclude ON t.sessionId = texclude.sessionId
WHERE
  /* and retrieve only those where these is *no match* on the joined subquery */
  texclude.sessionId IS NULL

示例:http ://sqlfiddle.com/#!2/14bda/2

于 2013-06-19T22:12:53.853 回答
1

这将过滤掉具有给定转码的会话 ID,然后计算其余部分:

select count(distinct sessionId) 
from transactions t1
where not exists (
    select 1 from transactions t2 
    where transCode = 103 and t1.sessionId = t2.sessionId
)
于 2013-06-19T22:15:20.377 回答