【发布时间】:2016-11-02 14:01:51
【问题描述】:
我这里有一张桌子:table1
employee ID Reporting Manager EmployeeName Week No. Points
1 Mr. A Bob week1 -10
2 Mr. A Deepak week1 50
3 Mr. B Brinda week1 60
4 Mr. B Chriss week1 -10
1 Mr. A Bob week2 -10
2 Mr. A Deepak week2 40
3 Mr. B Brinda week2 20
4 Mr. B Chriss week2 90
1 Mr. A Bob week3 -10
2 Mr. A Deepak week3 30
3 Mr. B Brinda week3 40
4 Mr. B Chriss week3 50
1 Mr. A Bob week4 -10
2 Mr. A Deepak week4 -10
3 Mr. B Brinda week4 -10
4 Mr. B Chriss week4 30
1 Mr. A Bob week5 -10
2 Mr. A Deepak week5 -10
3 Mr. B Brinda week5 20
4 Mr. B Chriss week5 50
在“周号”列中, 我有连续 5 周的数据,每周我都想检查这些情况-
1.每周我都会检查当周的积分。如果当周的积分值为-10,而前一周的积分也是-10,则在表2(下表)的totalpoints字段中添加-40那个特定的员工。(请参阅 EmployeeName 列)
2.我们再次检查本周和前两周的积分。如果连续三周得分为-10,则该人的奖励为-100,并添加到表2中的总积分字段中。(下表)
3。 同样连续四个星期,即本周和前 3 周,如果积分为 -10 ,则将 -200 添加到 table2 的总积分字段。
employee ID Employee Name Total points
1 Bob -50
2 Deepak 110
3 Brinda 130
4 Chriss 210
可能的解决方案(错误):
; WITH
n as (
select [EmployeeName], CAST(SUBSTRING([Week No.],5,10) AS INT) as wk, Points as pt
from YourTable --> Change this to your table
),
sc as (
select w.*, case w.pt when -10 then (case w1.pt when -10 then (case w2.pt when -10 then (case w3.pt when -10 then -200 else -100 end) else -40 end) else 0 end) else 0 end x
from n w
left join n w1 on w.[EmployeeName] = w1.[EmployeeName] and w.wk = w1.wk+1
left join n w2 on w.[EmployeeName] = w2.[EmployeeName] and w.wk = w2.wk+2
left join n w3 on w.[EmployeeName] = w3.[EmployeeName] and w.wk = w3.wk+3
),
l as (
select *, pt+x as total
from sc
),
s as (
select [EmployeeName], sum(total) total
from l
group by [EmployeeName]
)
select *
from s
谁能帮助我实现这一目标?我正在使用 sql server 2012。
【问题讨论】:
-
你需要检查LEAD and LAG
-
感谢您的输入。让我看看。 @JuanCarlosOropeza
-
案例 3. 不应该是 -150 而不是 -200?在第一个之后每 -10 -50?
-
积分奖励是针对每个案例,不相关。无论哪个案例满足,都会运行其相关查询并相应奖励积分。这就是为什么奖励的积分可以是-200或-150或-500。我的观点是价值不应该重要。谢谢。 @JuanCarlosOropeza
-
你能在你的输出中加入什么值吗?像评论一样添加它吗?喜欢
-- -10 -10 -50 -10并解释原因。
标签: sql sql-server sql-server-2012