SQL删除并过滤类似的结果

时间:2014-03-28 03:30:54

标签: sql sql-server

我有下面的查询,它给我一个地址出现两次的订单列表,这样我们可以将相同的订单重复包装到同一地址

select * from Orders
where 
address in (select address from orders group by address having count(*) = 2)




CustID     StockID      Address             Company 
-----------------------------------------------------------------
1217        23185       1 Some Road         Stockton            
58458       23185       1 Some Road                     
58459       23185       4 John St                       
58457       23185       4 John St                       
299576      23185       9 Roadway PDE       Graceland           
59470       23185       9 Roadway PDE       Cahill Tow          
97656       23185       24 Kent St                      
97677       23185       24 Kent St                      
212732      23185       23 Best Rd                      
226583      23185       23 Best Rd          c/o John            
191718      23185       98 King St                      
156363      23185       98 King St                      
121106      23185       19 Broadway                     
156362      23185       19 Broadway             

我希望结果看起来像这样,排除任何出现的地址,这两个地址在两个结果中都有公司名称。某些地址在公司名称中没有任何内容,但是如果同一地址的其他结果包含公司名称,我也希望将它们排除在外。

CustID     StockID      Address             Company 
-----------------------------------------------------------------
58459       23185       4 John St                       
58457       23185       4 John St                       
97656       23185       24 Kent St                      
97677       23185       24 Kent St                      
191718      23185       98 King St                      
156363      23185       98 King St                      
121106      23185       19 Broadway                     
156362      23185       19 Broadway             

希望这一切都有意义,并感谢任何帮助

谢谢!

2 个答案:

答案 0 :(得分:0)

select * from Orders o1 where 0 = (select count(*) from orders o2 where o1.address = o2.address and company is not null)  这是一个相关的子查询,它将主查询和子查询连接在一起。我假设&#34;空&#34;公司为NULL,如果您不使用空值,则替换为<> ""

答案 1 :(得分:0)

AS @ ClockWork-Muse在评论中提到,在这种情况下,您需要考虑很多事情,涉及数据清洁度和业务逻辑。话虽如此,您可以尝试这个问题:

;with filtered as
(
select * from Orders
where 
address in (select address from orders group by address having count(*) = 2)
)
,cte as
(select address, max(company) as max
from filtered
group by address
having max(company) = '')
select f.* from filtered f
inner join cte c on f.address = c.address

基本上,您创建一个CTE来识别那些只有Company空值的公司,然后再加入到您的查询结果