我想查询根据每个customer_part_number,cp_rev   找出dept_name字段中"钻孔" 在 "字符"后面出现的customer_part_number,cp_rev,根据下面的条件,查询出来的数据为:
customer_part_number   cp_rev
P01AL005501              00
 
--sql 语句如下
create table #tmp
(
  customer_part_number varchar(20),
  cp_rev varchar(5),
  step_number int,
  dept_code char(3),
  dept_name varchar(20)
)insert into #tmp 
select 'P01AL005501','00',1,'C05','压合'  
union all
select 'P01AL005501','00',2,'P01','单面湿绿油'                    
union all
select 'P01AL005501','00',3,'G03','字符' 
union all
select 'P01AL005501','00',4,'B01','钻孔'        
union all
select 'P01AL005501','0A',1,'C05','压合'  
union all
select 'P01AL005501','0A',2,'P01','单面湿绿油'                    
union all
select 'P01AL005501','0A',3,'G03','钻孔'                                                                           
union all
select 'P01AL005501','0A',4,'I01','V-CUT' 
union all
select 'P01AL005501','0A',5,'B01','字符'      --后面union all语句 省略...... 

解决方案 »

  1.   

    select customer_part_number,cp_rev from #tmp t where not exists(select 1 from #tmp where customer_part_number = t.customer_part_number
    and step_number<t.step_number and dept_name='钻孔' ) and dept_name ='字符'
      

  2.   

    SELECT * FROM #TMP T
    WHERE T.DEPT_NAME IN ('字符','钻孔')
    AND NOT EXISTS(SELECT NULL FROM #TMP WHERE T.CUSTOMER_PART_NUMBER=#TMP.CUSTOMER_PART_NUMBER
     AND #TMP.STEP_NUMBER<T.STEP_NUMBER AND #TMP.DEPT_NAME='钻孔')
    AND DEPT_NAME ='钻孔'customer_part_number cp_rev step_number dept_code dept_name
    -------------------- ------ ----------- --------- --------------------
    P01AL005501          0A     3           G03       钻孔(1 row(s) affected)
      

  3.   

    --还有一个条件  customer_part_number ,cp_rev相同,钻孔出现在字符之后
    SELECT * FROM #TMP T
    WHERE T.DEPT_NAME IN ('字符','钻孔')
    AND NOT EXISTS(SELECT NULL FROM #TMP WHERE T.CUSTOMER_PART_NUMBER=#TMP.CUSTOMER_PART_NUMBER
                      and #TMP.cp_rev<T.cp_rev
                                         AND #TMP.STEP_NUMBER<T.STEP_NUMBER AND #TMP.DEPT_NAME='钻孔')
    AND DEPT_NAME ='钻孔'