尝试在sql server中替换与Correlated子查询交叉

时间:2015-06-09 05:12:36

标签: sql-server

我正在尝试学习相关子查询并尝试用它替换交集集合运算符。但是子查询不会让我感到困惑。有人能说出原因吗?真的很感激。

select custid,empid
from sales.Orders
where orderdate>='20080101' and orderdate<('20080201')
intersect
select custid,empid
from sales.Orders
where orderdate>='20080201' and orderdate<('20080301');


select b.custid,b.empid
from sales.Orders as b
where exists
(select * from sales.Orders as a where a.orderid=b.orderid and a.orderdate>='20080101' and a.orderdate<'20080201')
and
exists
(select * from sales.Orders as c where c.orderid=b.orderid and c.orderdate>='20080201' and c.orderdate<'20080301')
order by b.custid 

2 个答案:

答案 0 :(得分:0)

您与orderid以及custidempid上应该关联的内容相关联。

select b.custid,
       b.empid
from sales.Orders as b
where exists (
             select * 
             from sales.Orders as a 
             where a.custid=b.custid and 
                   a.empid=b.empid and 
                   a.orderdate>='20080101' and 
                   a.orderdate<'20080201'
             ) and
      exists (
             select * 
             from sales.Orders as c 
             where c.custid=b.custid and 
                   c.empid=b.empid and 
                   c.orderdate>='20080201' and 
                   c.orderdate<'20080301'
             )
order by b.custid 

但是,由于intersect从结果中删除了重复项,因此此查询不会给出完全相同的结果。这可以通过在相关版本中使用distinct来解决。

答案 1 :(得分:0)

您甚至可以将GROUP BYHAVINGCASE一起使用

SELECT custid,empid
FROM sales.Orders
WHERE (orderdate>='20080101' and orderdate<('20080201')) OR (orderdate>='20080201' and orderdate<('20080301'))
GROUP BY custid,empid
HAVING SUM(CASE WHEN orderdate>='20080101' and orderdate<('20080201') THEN 1 ELSE 0 END) > 1
AND SUM(CASE WHEN orderdate>='20080201' and orderdate<('20080301') THEN 1 ELSE 0 END) > 1