有人可以告诉我如何从桌子中选择一个独特的城市/州组合吗?我知道您可以使用
选择不同的值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
.
.
.
正如您所看到的,这些组合并不是唯一的(华盛顿特区有多个列表)我只需要显示一次出现的城市/州组合
答案 0 :(得分: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}的供应商。也就是说,没有其他供应商共享{州,城市}的供应商。
你也可以这样做:
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