我有2张桌子
query1 table
case_no
1. 2761936
2. 2762090
3. 2762049
query_2表
case_no lawyer_id
2762090 215444
2762090 118999
2762049 180444
我想报告lawyer_id所在的记录> 100000和lawyer_id> = 200000 如果lawyer_id在该范围内,我根本不想要case_no。理想情况下报告应该只显示2761936和2762049
我尝试了以下方法,但它不起作用:
SELECT
q1.Case_no,q1.Form_no,q2.lawyer_id
FROM
[sample].[dbo].[Query1] Q1,
[sample].[dbo].[Query2] q2
where
q1.Case_no = q2.case_no
and q1.case_no not in(
select
q1.case_no
from
[sample].[dbo].[Query2] q2
where
q2.lawyer_id < 100000 and q2.lawyer_id >= 200000 )
答案 0 :(得分:1)
根本不需要使用NOT IN
子查询。使用简单的WHERE
:
BETWEEN
子句
SELECT
q1.Case_no,
q1.Form_no,
q2.lawyer_id
FROM
[sample].[dbo].[Query1] Q1
JOIN [sample].[dbo].[Query2] q2 ON q1.Case_no = q2.case_no
WHERE
q2.lawyer_id BETWEEN 100000 AND 200000
答案 1 :(得分:1)
由于lawyer_id永远不能同时为&lt; 100000和200000以上你永远不会得到任何结果。
你可能想要:
q2.lawyer_id < 100000 OR q2.lawyer_id >= 200000
OR
NOT (q2.lawyer_id >= 100000 AND q2.lawyer_id <= 200000)
OR
NOT (q2.lawyer_id BETWEEN 100000 AND 200000)
我重写了你的SQL:
SELECT A.CASE_NO,
A.FORM_NO,
B.LAWYER_ID
FROM [sample].[dbo].[Query1] A,
[sample].[dbo].[Query2] B
WHERE A.CASE_NO = B.CASE_NO
AND NOT (B.LAWYER_ID BETWEEN 100000 AND 200000)
答案 2 :(得分:1)
根据您的预期结果,我推断出您想要:
在哪种情况下:
WITH query1
AS
(
SELECT *
FROM (
VALUES (2761936),
(2762090),
(2762049)
) AS T (case_no)
),
query2
AS
(
SELECT *
FROM (
VALUES (2762090, 215444),
(2762090, 118999),
(2762049, 180444)
) AS T (case_no, lawyer_id)
)
SELECT case_no
FROM query1 -- sample.dbo.query1
EXCEPT
SELECT case_no
FROM query2 -- sample.dbo.query2
WHERE lawyer_id < 100000
EXCEPT
SELECT case_no
FROM query2 -- sample.dbo.query2
WHERE lawyer_id >= 200000;
也许你想要重构查询,例如
SELECT case_no
FROM query1 -- sample.dbo.query1
EXCEPT
SELECT case_no
FROM query2 -- sample.dbo.query2
WHERE ( lawyer_id < 100000
OR lawyer_id >= 200000 );