假设我有以下Oracle数据库表user_data
:
USER Manager Country
User 1 Manager 1 Canada
User 2 Manager 2 Canada
User 3 Manager 3 Canada
User 4 Manager 1 England
User 5 Manager 1 Scotland
User 6 Manager 1 Scotland
User 7 Manager 1 Scotland
User 8 Manager 1 England
我们有一项业务规则,即如果经理只是该国用户的唯一经理,则该经理只负责一个国家/地区。例如,根据提供的数据,经理1仅负责苏格兰和英格兰,但不负责加拿大。我有一个解决方案,但它很慢,我认为必须有更好的方法来查询数据:
SELECT DISTINCT manager, country
FROM user_data
WHERE country IN (
SELECT country FROM (
SELECT DISTINCT country, manager
FROM user_data
)
GROUP BY country
HAVING count(country) = 1
);
更高效查询的任何想法,确定哪个经理负责一个国家/地区?
答案 0 :(得分:1)
您可以尝试使用left join
和is not null
:
select distinct t1.manager
from user_data t1
left join (
select country
from user_data
group by country
having count(distinct manager) = 1) t2 on t1.country = t2.country
where t2.country is not null
答案 1 :(得分:0)
检查stragg()函数这可能是hepl,我没有在sql下面测试过。
SELECT stragg(manager), country
FROM user_data
GROUP BY country
HAVING count(country) = 1