我的继承数据库存在问题,最初设置它的人只留下很少的文档。
我有一组用户,每个用户有三个潜在的职业。查询时,它返回如下值:
USER_ID CAREER_ID TITLE
1 44 Agricultural Engineer
1 136 Educational Psychologist
1 132 Clinical Psychologist
18 245 3D Designer
18 2 Accountant - Private Practice
18 1 Accountant - Industry and Commerce
19 245 3D Designer
19 2 Accountant - Private Practice
19 1 Accountant - Industry and Commerce
20 128 Advice Centre Worker
20 130 Careers Adviser
20 129 Care Assistant
21 1 Accountant - Industry and Commerce
21 245 3D Designer
21 2 Accountant - Private Practice
23 245 3D Designer
23 2 Accountant - Private Practice
23 1 Accountant - Industry and Commerce
29 245 3D Designer
29 2 Accountant - Private Practice
29 1 Accountant - Industry and Commerce
30 219 PC Games Tester
30 173 Bouncer
30 103 Stunt Person
32 245 3D Designer
27 2 Accountant - Private Practice
27 1 Accountant - Industry and Commerce
27 245 3D Designer
30 219 PC Games Tester
30 173 Bouncer
30 103 Stunt Person
正如您所看到的,由于某种原因,职业1,2和245被设置为默认值。现在,我想过滤掉具有该特定职业集的用户,但不是所有用户的实例,因为任何用户都可以合法地选择一个或两个集合。
我可以过滤掉可能实际上有意选择那个特定集合的奇怪角色。
希望有人可以提供帮助。我确信解决方案很简单,但我无法想出来。
答案 0 :(得分:1)
Select ...
From Occupations O
Where Not Exists (
Select 1
From Occupations O1
Where O1.Career_Id In(1,2,245)
And O1.User_Id = O.User_Id
Group By O1.User_Id
Having Count(*) = 3
)
另一种解决方案:
Select ...
From Occupations O
Where Exists (
Select 1
From Occupations O1
Where O1.Career_Id Not In(1,2,245)
And O1.User_Id = O.User_Id
)
上述解决方案的问题在于,它将排除那些只有少于三个默认职业的人。即,它将排除仅具有(1,2),(1,245),(2,245),(1),(2),(245)的用户。如果他们必须拥有全部三个而且只有那三个,那么你需要像这样修改这个解决方案:
Select ...
From Occupations O
Where Exists (
Select 1
From Occupations O1
Where O1.Career_Id Not In(1,2,245)
And O1.User_Id = O.User_Id
)
Or Exists (
Select 1
From Occupations O2
Where O2.User_Id = O.User_Id
Having Count(*) < 3
)
答案 1 :(得分:0)
我认为这应该确定列出了职业1,2和245的用户:
SELECT User_ID
FROM Occupations
WHERE Career_ID IN (1, 2, 245)
GROUP BY Career_ID
HAVING COUNT(*) = 3
如果您想要那些没有这套职业的用户列表,那么:
SELECT User_ID
FROM Occupations
WHERE User_ID NOT IN
(SELECT User_ID
FROM Occupations
WHERE Career_ID IN (1, 2, 245)
GROUP BY Career_ID
HAVING COUNT(*) = 3)
答案 2 :(得分:0)
假设您有一个用户表,职业表和一个映射表(user_career_map),那么这将为您提供所需内容:
SELECT user_id, career_id, title
FROM (
SELECT distinct m.user_id, m.career_id, c.title
, sum(case when m.career_id in (1, 2, 245) then 1 else 0 end) over (partition by m.user_id) filter
FROM user_career_map m inner join career c on m.career_id = c.career_id
) WHERE filter <> 3
ORDER BY user_id, career_id;