如何按多列过滤订单号

时间:2015-08-07 18:13:55

标签: sql sql-server

我有一个包含很多行的表,看起来像这样:

Order_id Part_id    Description   GL_code
12345    Gk123      Gun mount     6850
12345    null       Freight       4050.2
12346    Blac       Lock          6790
12346    null       Freight       4050

我想创建一个查询,返回part_idGK% numberBlac number的所有订单信息,订单的运费GL_code为{{1} }}。

4050.2位于说明列中,与Freight不同。

我不想在订单中包含所有part_idBlac GK% partsfreight

我只能获得所有4050.2或全部GK%和Blac's。

3 个答案:

答案 0 :(得分:2)

一种方法是使用相关子查询,确保使用货运代码4050.2存在同一订单的行:

select * from tab t
where (Part_id = 'Blac' or Part_id like 'GK%') 
and exists (
    select 1 
    from tab 
    where Order_id = t.Order_id 
      and Description = 'Freight' 
      and GL_code = '4050.2' -- remove the quotes if this is a number and not a char value
    )

使用您的样本数据,这将返回:

Order_id    Part_id Description GL_code
12345       Gk123   Gun mount   6850    

另一个选择是使用纯粹基于集合的查询:

select Order_id from tab where (Part_id = 'Blac' or Part_id like 'GK%')
intersect 
select Order_id from tab where Description = 'Freight' and GL_code = '4050.2'

或者,如果您只想要使用Freight的行,您可以反转条件:

select * from shipper_line t
where Description = 'Freight' and GL_code = '4050.2' 
and exists (
    select 1 
    from shipper_line 
    where Order_id = t.Order_id 
      and (Part_id = 'Blac' or Part_id like 'GK%') 
);

答案 1 :(得分:0)

最简单的方法就是把桌子加到自己身上; SQL在跨列检查方面比跨行检查更好。

Select a.* from MyTable a
inner join MyTable b
on a.Order_ID = b.Order_ID and b.Part_ID is null and b.Description = 'Freight' and b.GL_code = 4050.2
where (a.Part_ID like 'GK%' or a.Part_ID like 'Blac%')

您还可以使用exists或子查询:

select * from MyTable a
where (a.Part_ID like 'GK%' or a.Part_ID like 'Blac%')
and exists 
  (select 1 from MyTable b 
  where a.order_ID = b.order_ID and b.Description = 'Freight' and b.GL_code = 4050.2)

select * from MyTable a
where (a.Part_ID like 'GK%' or a.Part_ID like 'Blac%')
and order_ID in 
  (select order_ID from MyTable 
  where Description = 'Freight' and GL_code = 4050.2)

编辑:这是一个SQL小提琴:http://sqlfiddle.com/#!6/a778c/1/0

答案 2 :(得分:0)

请尝试此查询。根据你的问题,这似乎也符合重要条件:

  

Freight位于说明列中,与行不同   part_id。

select l.order_id from 
(
select order_id,rownum from 
   (
     select *, row_number() over (partition by order_id order by Part_id, Description, GL_code ) as rownum from tblt
   ) t 
where (part_id like 'GK%' or part_id like 'Blac%')  and order_id in (select order_id from tblt where GL_code like '4050.2')
) l
inner join 
 (select * from 
   (
     select *, row_number() over (partition by order_id order by Part_id, Description, GL_code ) as rownum 
     from tblt
   ) t2 
where t2.description like 'Freight') r
on l.order_id=r.order_id and l.rownum<>r.rownum

小提琴链接:http://sqlfiddle.com/#!6/620c05/8