在SQL Server中获取两个查询之间的区别

时间:2017-12-12 09:38:02

标签: sql-server sql-server-2008

我正在开发设计不佳的数据库。我需要查询表以找到以下问题的解决方案。

假设我有一张这样的桌子。

+------------+------------+--------------+-----------+
|     id     | SubCode    | Type         | NumId     |
+----------------------------------------------------+
|      1     | SB1212     | TCH          | 100000000 |
|      1     | SB1212     | APP          | 100000000 |
|      1     | SB1212     | TCH          | 100000001 |
|      1     | SB1212     | APP          | 100000002 |
+----------------------------------------------------+

我需要找到属于 Type ='TCH'的人的NumId(他们不应属于Type ='APP')。

请注意,NumId可以重复。

我编写了以下查询,并且需要花费太多时间来加载。这看起来像一个简单的问题,但我正在研究这个问题太长时间以至于现在看不到解决方案。有人能指出我在哪里做错了吗?

SELECT NumId 
FROM TeacherSubject 
WHERE SubCode = 'SB1212' 
  AND Type = 'TCH' OR Type = 'APP' 
  AND id NOT IN (SELECT NumId FROM TeacherSubject 
                 WHERE SubCode = 'SB1212' 
                   AND Type = 'APP') 
ORDER BY NumId DESC

我期待的输出是 100000001 。因为 100000000 属于TCH和APP类型。

2 个答案:

答案 0 :(得分:3)

您可以使用CTE

with cte as (
select * 
  from TeacherSubject 
 where [Type] = 'APP'
   and Subcode = 'SB1212'
) 
select NumID 
  from TeacherSubject 
 where [Type] = 'TCH'
   and Subcode = 'SB1212' 
   and NumID not in (select NumID from cte)
 order by NumID desc

答案 1 :(得分:1)

试试这个

SELECT
    NumId
    FROM YourTable YT
        WHERE [Type] = 'TCH'
AND SubCode = 'SB1212'
                AND NOT EXISTS
                (
                    SELECT
                        1
                        FROM YourTable
                            WHERE NumId = YT.NumId
                                AND [Type] <> YT.[Type]
AND [SubCode] = YT.SubCode
                )