[英]Checking the pair rows using SQL Server query
Sample Database: 样本数据库:
workerid codes empl_rcd
123 USA 0
123 NY 0
123 SF 0
123 USA 1
123 NY 1
567 USA 1
567 CA 1
567 CA 2
567 NY 1
890 USA 0
890 NY 0
890 USA 2
890 NY 1
requirement: for each worker if USA is present check the corresponding NY is present or not 要求:对于每个工人(如果存在美国,请检查是否存在相应的纽约)
eg for worker 123 if USA 0 is present then check NY 0 is present or not if USA 1 is present then check NY 1 is present or not similar for other workerids also 例如,对于工人123,如果存在USA 0,则检查NY 0是否存在,如果是否存在USA 1,则对于其他workerid,也检查NY 1是否存在或相似
Resultant output should be : 结果输出应为:
123 USA 0
123 NY 0
123 USA 1
123 NY 1
567 USA 1
567 NY 1
890 USA 0
890 NY 0
try this: 尝试这个:
select * from yourtable f1
where f1.codes in ('USA', 'NY')
and exists
(
select * from yourtable f2
where (f1.codes='USA' and f2.codes='NY' or f1.codes='NY' and f2.codes='USA')
and f1.workerid=f2.workerid and f1.empl_rcd=f2.empl_rcd
)
Solution 2: 解决方案2:
with perimeter as (
select f1.*, case when f1.codes='USA' then 'NY' else 'USA' end CodesSearch
from yourtable f1
where f1.codes in ('USA', 'NY')
)
select f1.* from perimeter f1
and exists
(
select * from perimeter f2
where f1.CodesSearch=f2.codes and f1.workerid=f2.workerid and f1.empl_rcd=f2.empl_rcd
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.