选择记录等于y但不是x的用户

时间:2016-01-12 16:13:07

标签: sql sql-server tsql

我有一张表格,其中包含参赛者参赛选票的历史记录。结构的简化示例是:

id | entrantId | roundId | judgeId

一些示例数据:

401 | 32 | 3 | 4
402 | 32 | 3 | 5
403 | 35 | 3 | 4
404 | 32 | 4 | 4
405 | 36 | 3 | 4
406 | 36 | 3 | 10

我需要获得拥有judgeId = 4roundId = 3但同一个' entrantId'没有roundId = 4

的任何类型的记录

因此,使用上述数据,我希望检索记录403405,因为这些参赛者(35& 36)在第3轮中有法官4的记录,但没有圆形记录4(例如roundId = 4)

我假设我需要一个使用' IN'的SELECT语句。基于条款,但我对此知之甚少,无法构建合适的查询。

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:9)

您可以使用相关子查询:

SELECT *
FROM tab t1
WHERE judgeId = 4 
  AND roundId = 3
  AND NOT EXISTS (SELECT 1
                  FROM tab t2
                  WHERE t1.entrantId = t2.entrantId
                    AND t2.roundId = 4);

LiveDemo

输出:

╔═════╦═══════════╦═════════╦═════════╗
║ id  ║ entrantId ║ roundId ║ judgeId ║
╠═════╬═══════════╬═════════╬═════════╣
║ 403 ║        35 ║       3 ║       4 ║
║ 405 ║        36 ║       3 ║       4 ║
╚═════╩═══════════╩═════════╩═════════╝

<小时/> 或者使用窗口函数:

WITH cte AS(
SELECT *,
  c = COUNT(CASE WHEN roundId = 4 THEN 1 END) OVER (PARTITION BY entrantId)
FROM #tab
)
SELECT id,entrantId,roundId,judgeId
FROM cte
WHERE c = 0
  AND judgeId = 4 
  AND roundId = 3;

LiveDemo2

答案 1 :(得分:0)

你可以使用除外,但你不会得到身份证。

select entrantId 
  from table 
 where roundId = 3 and judgeId = 4 
except 
select entrantId 
  from table 
 where roundId = 4;

答案 2 :(得分:-2)

简单且最具可读性和直接使用NOT IN子查询如下

SELECT * FROM Votes WHERE judgeId = 4 AND roundId = 3
AND entrantId NOT IN (SELECT entrantId FROM Votes WHERE roundId = 4)