ReportingDirector ManagerID EmployeeName EmployeeID WeekNumber Pointsrewarded
john(director) 1 a 11 week1 100
john(director) 1 b 22 week1 200
john(director) 1 c 33 week1 300
bob(director) 2 d 44 week1 -10
bob(director) 2 e 55 week1 30
bob(director) 2 f 66 week1 40
bob(director) 2 g 77 week1 50
bob(director) 2 h 88 week1 90
cavin(director) 3 i 99 week1 300
cavin(director) 3 j 100 week1 400
cavin(director) 3 k 111 week1 800
cavin(director) 3 l 222 week1 305
cavin(director) 3 m 333 week1 23
cavin(director) 3 n 444 week1 44
alpha (senior Director) 111 john 1111 week1 455
alpha(senior Director) 111 bob 2222 week1 -10
alpha(senior Director) 111 cavin 3333 week1 77
x x mr.aplha 1 week1 99
我上面有一张桌子。这里我们有三个职位employees
,director
和senior director
。员工属于董事,董事是高级董事。
问题:如果导演下的任何人有-10分(plz见pointsReawrded
列)-10,那么导演得到-100分,即在{}中加上-100分{1}}相应导演的专栏。如果没有员工,在他/她之下有-10,那么导演会得到200分的奖励。
例如,表中的员工'd'是bob,他是董事。所以-100被奖励给鲍勃。再一次,约翰下的人没有-10,所以约翰获得了200分的奖励。
我们不会将任何积分奖励给'alpha',即使他下面的任何员工的积分为-10,因为他位于链的顶端。
任何人都可以帮助我进行一般化查询,以检查导演下的任何员工是否得分为-10,并且该导演的得分为-100分。如果不是200分的奖励。
答案 0 :(得分:1)
尝试这样的事情
;with cte as
(
select ReportingDirector, ManagerID, EmployeeName, EmployeeID, WeekNumber, Pointsrewarded
,COUNT(IIF(Pointsrewarded < 0,0,null))
over (partition by ReportingDirector order by ReportingDirector) as grp
from #tmp1
where ReportingDirector = ''
UNION ALL
select a.ReportingDirector, a.ManagerID, a.EmployeeName, a.EmployeeID, a.WeekNumber, a.Pointsrewarded
,COUNT(IIF(a.Pointsrewarded < 0,0,null))
over (partition by a.ReportingDirector order by a.ReportingDirector) as grp
FROM #tmp1 a
join cte on a.ManagerID = cte.EmployeeID
)
select cte.*, IIF(grp = 1, -100,200) MgrPointsRewarded
from cte
where ReportingDirector <> ''