查询表并与另一个查询进行比较(如果存在,则显示在结果中)

时间:2015-09-04 21:05:24

标签: sql sql-server

这是表格测试

ID          order_no      film_type   process   line
100         RXQFW40-1       FW          SL      HL21
101         RXQFW46-1-1     EXFW        EX      HE15
103         RXQFW49-1       FW          SL      HL21
173         RXQFW49-1-1     EXFW        EX      HE15
107         RXQFW4E-1       FW          SL      HL21
115         RXQFW4E-1       FW          SL      HL21
169         RXQFW4E-1-1     EXFW        EX      HE13
168         RXQFW4E-1-1     EXFW        EX      HE13
104         RXQFW4K-1       FW          SL      HL21
172         RXQFW4K-1-1     EXFW        EX      HE15

首先,我想过滤流程=' SL'并获得order_no的前7个字符。

Select distinct substring(order_no,1,7) where process='SL' from test

下一步

如果结果符合

Select distinct substring(order_no,1,7) where process='EX' from test

这将是输出:

order_no
RXQFW49-1 
RXQFW4E-1 
RXQFW4K-1 

4 个答案:

答案 0 :(得分:1)

您可以通过组合两个查询

来使用下面的WHERE EXISTS
Select distinct substring(order_no,1,7) 
from test t
where process='EX' 
and EXISTS ( Select 1 from test 
where process='SL' 
and substring(t.order_no,1,7) = substring(order_no,1,7));

答案 1 :(得分:1)

EXISTS使用JOIN结果substring SL.order_no的另一种方法。并且更容易阅读。

看起来结果始终是SELECT DISTINCT SL.order_no FROM test SL inner join test EX on substring(SL.order_no,1,7) = substring(EX.order_no,1,7) WHERE SL.process = 'SL' AND EX.process = 'EX' 所以不需要在那里应用另一个子字符串。

SQL Fiddle Demo

{{1}}

答案 2 :(得分:0)

加入他们:

select distinct sl.ord from 
( Select distinct substring(order_no,1,7) ord where process='SL' from test ) sl
,( Select distinct substring(order_no,1,7) ord where process='EX' from test ) ex
where sl.ord = ex.ord

答案 3 :(得分:0)

你可以尝试一下吗?

Select t.ord
from test t 
where process = 'SL' 
   AND
   exists (select * from test t2 where left(t.order_no,7) = left(t2.order,7) AND process = 'EX')