假设我有以下信息:
First_Name Last_Name Title Branch Location
John Johnson Manager NY
Jack Smith Internet Manager NY
Chris Jones Internet Manager NY
Harold O'Reilly Executive NY
Liz Young Manager WA
Trey Ritter Manager WA
Rick Morgan Executive NC
Allison Hubbard Internet Manager NC
Holly Dietz Executive FL
我希望应用以下逻辑:
如果某个地点有互联网管理员,则可以删除其他记录(执行管理员)。如果有多个所述互联网管理员,请保留这些记录。
如果没有互联网管理员
因此,从本质上讲,结果应如下所示:
First_Name Last_Name Title Branch Location
Jack Smith Internet Manager NY
Chris Jones Internet Manager NY
Liz Young Manager WA
Trey Ritter Manager WA
Allison Hubbard Internet Manager NC
Holly Dietz Executive FL
我知道我可能不得不使用EXISTS条件或类似的东西,但我不确定从哪里开始。如何实现所需的输出?
答案 0 :(得分:2)
我将通过以下步骤查看此问题:
所以,从第1步开始:
select Branch_Location,
[titleFlag] = min(case
when Title='Internet Manager' then 1
when Title='Manager' then 2
when Title='Executive' then 3
else 999
end)
from table
group by Branch_location
然后,使用步骤1作为连接上的子查询(我将使用CTE语句将其分开):
;with bestTitle as (
select Branch_Location,
[titleFlag] = min(case
when Title='Internet Manager' then 1
when Title='Manager' then 2
when Title='Executive' then 3
else 999
end)
from table
group by Branch_location
)
select n.*
from table n
join bestTitle t on n.Branch_Location=t.Branch_Location
and n.Title = case t.titleFlag
when 1 then 'Internet Manager'
when 2 then 'Manager'
when 3 then 'Executive'
else 'This is an unknown condition...'
end
正如您所看到的,我并不真正使用if
语句,而是使用case
语句来正确排序/优先处理标题。从那里,第1步子查询确定每个分支的查找内容,第2步外部查询查找满足这些条件的记录。