0

我有表 [Contracts],其中包含 [id]、[number] 列。而且我还有一些字符串格式的数字:'12342'、'23252'、'1256532'。我想得到这样的输出。

1535325 | no
12342   | yes
23252   | yes
434574  | no
1256532 | yes

当然我可以写这个并获取我拥有的行,但是我如何确定该行是否不存在并获得上面的输出:

SELECT [Id]
      ,[Number]
  FROM [Contracts]
  where [Number] in 
  ('12342', '23252', '1256532')
4

1 回答 1

1

您可以将值放入临时表或表变量中并执行以下操作left join

declare @d table (Number varchar(10))
insert into @d values  ('12342'), ('23252'), ('1256532'), ('xxxx') -- last one is not in Contracts

SELECT c.[Id], c.[Number], case when d.Number is NULL then 'no' else 'yes' end [This Number from C is in D also]
FROM [Contracts] c
    left join @d d on d.Number = c.Number

用于“相反”用途right join

SELECT c.[Id], d.[Number], case when c.Number is NULL then 'no' else 'yes' end [This Number from D is in C also]
FROM [Contracts] c
    right join @d d on d.Number = c.Number
于 2013-07-25T10:11:36.833 回答