>编写一个查询,将字符串附加到所选字段,指示指定的销售人员是否与其所在城市的客户匹配?
salesman_id | name | city | commission
-------------+------------+----------+------------
5001 | James Hoog | New York | 0.15
5002 | Nail Knite | Paris | 0.13
5005 | Pit Alex | London | 0.11
5006 | Mc Lyon | Paris | 0.14
5007 | Paul Adam | Rome | 0.13
5003 | Lauson Hen | San Jose | 0.12
customer_id | cust_name | city | grade | salesman_id
-------------+----------------+------------+-------+-------------
3002 | Nick Rimando | New York | 100 | 5001
3007 | Brad Davis | New York | 200 | 5001
3005 | Graham Zusi | California | 200 | 5002
3008 | Julian Green | London | 300 | 5002
3004 | Fabian Johnson | Paris | 300 | 5006
3009 | Geoff Cameron | Berlin | 100 | 5003
3003 | Jozy Altidor | Moscow | 200 | 5007
3001 | Brad Guzan | London | | 5005
这是提供的解决方案。
SELECT a.salesman_id, name, a.city, 'MATCHED'
FROM salesman a, customer b
WHERE a.city = b.city
UNION
(SELECT salesman_id, name, city, 'NO MATCH'
FROM salesman
WHERE NOT city = ANY
(SELECT city
FROM customer))
ORDER BY 2 DESC
这是我想到的解决方案,我想知道它是否会以与提供的解决方案相同的方式工作。
Select s.salesman_id, name, city,
case when s.city = c.city then 'Matched'
else 'No Match'
end as City_Match
from salesman s
join customer c
on s.salesman_id = c.salesman_id;
预期结果。
salesman_id name city ?column?
5005 Pit Alex London MATCHED
5007 Paul Adam Rome NO MATCH
5002 Nail Knite Paris MATCHED
5006 Mc Lyon Paris MATCHED
5003 Lauson Hen San Jose NO MATCH
5001 James Hoog New York MATCHED
将exists
与子查询一起使用:
select s.*,
(case when exists (select 1
from customer c
where c.salesman_id = s.salesman_id and
c.city = s.city
)
then 'MATCHED' else 'NO MATCH'
end) as flag
from salesman s;
您提供的示例查询是一个笑话。 它必须是:
- 它使用无意义的表别名。
- 它使用古老的逗号语法,而不是正确、明确、标准的
join
语法。 - 它依靠
union
来删除重复项,当这是不必要的开销时。 - 它使用的操作比所需逻辑所需的操作多得多。
第一个查询是(在第二部分中(查找没有客户的城市中的任何销售员。您查询正在查找销售员所在城市与客户所在城市匹配的情况。
使用左连接和 case 语句的等效查询为
Select distinct s.salesman_id, name, city,
case when c.city is not null then 'Match' else 'No Match' end as City_Match
from salesman s
left join customer c on s.city = c.city;