0

我有一个巨大的表格,其中包含送货地址信息和帐单地址信息。我可以在两个单独的表格中获得唯一的送货地址和帐单地址,其中包含以下内容:

SELECT DISTINCT ShipToName, ShipToAddress1, ShipToAddress2, ShipToAddress3, ShipToCity, ShipToZipCode
FROM Orders
ORDER BY Orders.ShipToName

SELECT DISTINCT BillToName, BillToAddress1, BillToAddress2, BillToAddress3, BillToCity, BillToZipCode
FROM Orders
ORDER BY Orders.BillToName

我怎样才能得到两者的不同交集?我不确定语法。

4

3 回答 3

2

像这样的东西?

SELECT DISTINCT
    toname, addr1,  addr2,  addr3,  city,   zip
FROM
    (SELECT DISTINCT 
        ShipToName AS toName, 
        ShipToAddress1 AS addr1, 
        ShipToAddress2 AS addr2, 
        ShipToAddress3 AS addr3, 
        ShipToCity AS city, 
        ShipToZipCode AS zip
    FROM 
        Orders

    UNION ALL

    SELECT DISTINCT 
    BillToName AS toName, 
    BillToAddress1 AS addr1, 
    BillToAddress2 AS addr2, 
    BillToAddress3 AS addr3, 
    BillToCity AS city, 
    BillToZipCode AS zip
    FROM 
        Orders) o
ORDER BY ToName
于 2013-01-10T19:33:46.730 回答
2

你说“交集”,但你接受了联盟的答案,所以我猜你只想要UNION DISTINCT. 不需要派生表和三个DISTINCT. 您可以使用简单的:

SELECT 
    ShipToName     AS Name, 
    ShipToAddress1 AS Address1, 
    ShipToAddress2 AS Address2, 
    ShipToAddress3 AS Address3, 
    ShipToCity     AS City, 
    ShipToZipCode  AS ZipCode
FROM 
    Orders

UNION                               --- UNION means UNION DISTINCT

SELECT  
    BillToName 
    BillToAddress1, 
    BillToAddress2,
    BillToAddress3,
    BillToCity,
    BillToZipCode
FROM 
    Orders 

ORDER BY
    Name ;
于 2013-01-10T20:00:58.043 回答
1

您可以在所有字段上加入这两个集合,这将返回匹配的记录:

SELECT *
FROM Orders o1
INNER JOIN Orders o2
    ON o1.ShipToName = o2.BillToName
    AND o1.ShipToAddress1 = o2.BillToAddress1
    AND o1.ShipToAddress2 = o2.BillToAddress2
    AND o1.ShipToAddress3 = o2.BillToAddress3 
    AND o1.ShipToCity = o2.BillToCity
    AND o1.ShipToZipCode = o2.BillToZipCode

或者您应该能够使用 INTERSECT:

SELECT ShipToName, ShipToAddress1, ShipToAddress2, ShipToAddress3, ShipToCity, ShipToZipCode
FROM Orders
INTERSECT
SELECT BillToName, BillToAddress1, BillToAddress2, BillToAddress3, BillToCity, BillToZipCode
FROM Orders

甚至是UNION查询(UNION删除两组数据之间的重复项):

SELECT ShipToName, ShipToAddress1, ShipToAddress2, ShipToAddress3, ShipToCity, ShipToZipCode
FROM Orders
UNION 
SELECT BillToName, BillToAddress1, BillToAddress2, BillToAddress3, BillToCity, BillToZipCode
FROM Orders
于 2013-01-10T19:20:47.717 回答