0

有人可以告诉我如何从表格中选择一个独特的城市/州组合吗?我知道您可以选择不同的值

SELECT DISTINCT city, state
FROM table

但我需要选择独特的组合。换句话说,我需要选择与另一个条目不具有相同城市/州值的组合。据我所知,这些是不同的。

我要做的是获取这些唯一值并列出带有供应商名称的城市/州组合。这是我到目前为止所拥有的:

SELECT v.vendor_name, v2.vendor_state, v2.vendor_city
FROM vendors v JOIN (SELECT DISTINCT vendor_state, vendor_city
                FROM vendors) v2
ON v.vendor_state = v2.vendor_state and v.vendor_city = v2.vendor_city

这导致

VENDOR_NAME                    VENDOR_STATE VENDOR_STATE
--------------------------------------------------------
Reiter's Scientific & Pro Books DC  Washington
Register of Copyrights          DC  Washington
National Information Data Ctr   DC  Washington
Zee Medical Service Co          IA  Washington
Small Press                     MI  Traverse City
Vision Envelope & Printing      CA  Gardena
Enterprise Communications Inc   VA  Mclean
Publishers Weekly               OH  Marion
.
.
.

如您所见,组合不是唯一的(华盛顿特区有不止一个列表)我只需要显示出现一次的城市/州组合

4

1 回答 1

1

我相信您正在寻找:

SELECT vendor_name, vendor_state, vendor_city
FROM vendors v
WHERE NOT EXISTS
(
    SELECT 1
    FROM vendors v2
    WHERE v2.vendor_id <> v.vendor_id
    AND v2.vendor_state = v.vendor_state
    AND v2.vendor_city = v.vendor_city
)

这将列出具有唯一 {state, city} 的供应商。也就是说,没有其他供应商共享相同 {state, city} 的供应商。


你也可以这样做:

SELECT v.vendor_name, v.vendor_state, v.vendor_city
FROM vendors v
INNER JOIN
(
    SELECT vendor_state, vendor_id
    FROM vendors
    GROUP BY vendor_state, vendor_id
    HAVING COUNT(1) = 1
) u ON v.vendor_state = u.vendor_state AND v.vendor_city = u.vendor_city
于 2013-02-25T07:25:22.463 回答