我想编写一个查询,该查询能够查看表的两列,如下所示:
表名“工资单”
Check_No Control_code
123456 PTS
123456 PT1012
123456 EAR 1012
123456 PTO0
123456 PTS
78910 PTS
78910 PTS
78910 PTO0
78910 PT102
78910 PT102
78910 PTO0
89456 PTS
89456 EAR 1012
89456 EAR 1012
89456 PT1012
89456 PTO0
89456 PTO0
对于此表,第一列是支票号码,一个支票号码可以具有多个control_code。我希望查询查看“控制代码”列,如果“ control_code” PTS存在但不存在EAR 1012,则查询一个检查号,然后给我检查号。
在此示例中,答案应为78910
请帮助。
下面是我尝试过的查询:
Select [Check_No]
from [Payroll]
Where [Control_Code]<>'EAR 1012'
And [Control Code]='PTS'
Order by [Check_No]
也:
Select [Check_No]
into #temp
from [payroll]
Where [Control_Code]='EAR 1012'
Select [Check_No]
from [payroll]
where [Check_No] not in
(Select [Check_No] from #temp)
答案 0 :(得分:1)
您可以使用not exists
:
select p.*
from payroll p
where p.control_code = 'PTS' and
not exists (select 1
from payroll p2
where p2.Check_No = p.Check_No and
p2.control_code = 'EAR 1012'
);