如何根据单个列值过滤重复行和过滤行?

时间:2016-08-10 16:47:43

标签: sql sql-server tsql

select co.id, udf.string_val, udf.id 

from customer_order co left join user_def_fields as udf on co.id = udf.document_id

where status = 'h' and order_date between '1/1/2016' and '12/31/2016' 

and co.id <> (select document_id from user_def_fields 

where (string_val = 'questions' or string_val = 'credit card' or string_val = 'credit hold' 
or string_val = 'design'))

co.id | String_val | udf.id
------|------------|--------
9798  | QUESTIONS  |UDF-000054 
9798  | RUSH ORDER |UDF-000047
9798  | RUSH ORDER |UDF-000024
9799  | RUSH ORDER |UDF-000047
9799  | RUSH ORDER |UDF-000024
9799  | DESIGN     |UDF-000054
9801  | RUSH ORDER |UDF-000047
9801  | RUSH ORDER |UDF-000024
9802  | NULL       |NULL
9803  | RUSH ORDER |UDF-000047
9803  | RUSH ORDER |UDF-000024
9803  | CHECKED    |UDF-000054

以下是没有任何过滤器的查询结果示例。 Co.id是订单号,各种string_vals是各自udf字段内的注释,udf.id是字段id,document_id是udf表中的订单号引用。客户服务进入紧急订单&#39;在两个领域,这就是它出现两次的原因。有时没有输入注释,并且udf字段为空。我真的只需要返回co.id结果并且是唯一的。从上面的数据示例中,我希望我的查询返回

co.id 
------
9801
9802
9803

我当前的查询给了我一个错误,因为它返回多个结果。

3 个答案:

答案 0 :(得分:1)

基本上,你想使用&#34; Distinct&#34;关键词。 Distinct将禁止结果集中的行与集合中已有的另一行具有完全相同的数据。问题是,如果您想要真正独特的co.id值,那么这是您能够返回的唯一列(非常类似于您想要的结果),因为distinct将返回所有行选择列表中任何字段的明显组合,如果co.idstring_val在结果之间有所不同,则仍可能为您提供重复的udf.id值。您的查询将如下所示:

select distinct co.id    
from customer_order co 
left join user_def_fields udf 
    on co.id = udf.document_id    
where status = 'h' and order_date between '1/1/2016' and '12/31/2016'     
and co.id not in (select document_id from user_def_fields
    where (string_val = 'questions' or string_val = 'credit card' 
        or string_val = 'credit hold' or string_val = 'design'))

答案 1 :(得分:0)

您可以使用DISTINCT关键字:

select distinct co.id
from customer_order co left join user_def_fields as udf on co.id = udf.document_id
where status = 'h' and order_date between '1/1/2016' and '12/31/2016' 
and co.id <> (select document_id from user_def_fields 
where (string_val = 'questions' or string_val = 'credit card' or string_val = 'credit hold' or string_val = 'design'))

答案 2 :(得分:0)

您可以这样做以避免使用DISTINCT。

SELECT  co.id
FROM    customer_order co
WHERE   status = 'h'
        AND order_date BETWEEN '1/1/2016' AND '12/31/2016'
        AND NOT EXISTS ( SELECT 1
                         FROM   user_def_fields udf
                         WHERE  udf.document_id = co.id
                                AND string_val IN ('questions','credit card','credit hold','design')  
        )

或者您可以使用左连接并检查空

SELECT  co.id
FROM    customer_order co
        LEFT JOIN user_def_fields udf ON udf.document_id = co.id 
            AND udf.string_val IN ('questions','credit card','credit hold','design') 
WHERE   co.status = 'h'
        AND order_date BETWEEN '1/1/2016' AND '12/31/2016'
        AND udf.document_id IS NULL