Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Script Library
 INTERSECT

Author  Topic 

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-02-10 : 06:50:05
Hi,
INTERSECT is a set operator. There are some alternative logical equivalence method for INTERSECT. Here are some solutions. I will glad to know a new useful query. Thanks
USE Northwind;

--INTERSECT
SELECT Country, Region, City
FROM Customers
INTERSECT
SELECT Country, Region, City
FROM Employees;


--UNION ALL
SELECT D.Country, D.Region, D.City
FROM (SELECT DISTINCT Country, Region, City
FROM Customers
UNION ALL
SELECT DISTINCT Country, Region, City
FROM Employees) AS D
GROUP BY D.Country, D.Region, D.City
HAVING COUNT(*) = 2;

--EXISTS
SELECT DISTINCT Country, Region, City
FROM Customers AS C
WHERE EXISTS
(SELECT *
FROM Employees AS E
WHERE COALESCE(C.Country, '1') = COALESCE(E.Country, '1')
AND COALESCE(C.Region, '1') = COALESCE(E.Region, '1')
AND COALESCE(C.City, '1') = COALESCE(E.City, '1'));

--IN
SELECT DISTINCT Country, Region, City
FROM Customers AS C
WHERE COALESCE(C.Country, '1') IN
(SELECT COALESCE(E.Country, '1')
FROM Employees AS E
WHERE COALESCE(C.Region, '1') = COALESCE(E.Region, '1')
AND COALESCE(C.City, '1') = COALESCE(E.City, '1'));


--JOIN
SELECT DISTINCT C.Country, C.Region, C.City
FROM Customers AS C
JOIN Employees AS E
ON COALESCE(C.Country, '1') = COALESCE(E.Country, '1')
AND COALESCE(C.Region, '1') = COALESCE(E.Region, '1')
AND COALESCE(C.City, '1') = COALESCE(E.City, '1');


--EXCEPT
SELECT Country, Region, City
FROM Customers
EXCEPT (SELECT Country, Region, City
FROM Customers
EXCEPT
SELECT Country, Region, City
FROM Employees);

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2010-02-10 : 07:23:12
Isn't this the same post as this?
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=131772



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -