检查连续值和更新字段

时间:2016-10-28 12:26:57

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2012

我在这里有一张桌子:

Table1

在“周无”栏中, 我有连续5周的数据,每周我都要查看这些条件 -

1.每周我都会检查当前周的积分。如果本周的积分值为-10,而前一周的积分也是-10,那么在总积分字段的表2(下表)中添加-40

2.我们检查当前周和前两周的分数。如果连续三周的分数为-10,则该人的奖励为-100,并添加到表2中的总分数字段。(下表)< / p>

3。 类似地,对于连续四周,即当前周和前一个3周,如果点为-10,则将-200添加到table2的总点数字段。

Table 2

任何人都可以帮我解决这个问题。 M使用sql server。

1 个答案:

答案 0 :(得分:2)

这是

; WITH 
u AS (SELECT * from (values (1,'Bob'),(2,'Deepak'),(3,'Brinda'),(4,'Chriss'),(4,'Chriss')) as d (usr,name)),
N AS (SELECT * from (values (1,1,-10),(1,2,-10),(1,3,-10),(1,4,-10),(1,5,-10),(2,1,50),(2,2,40),(2,3,30),(2,4,-10),(2,5,-10),(3,1,60),(3,2,20),(3,3,40),(3,4,-10),(3,5,20),(4,1,-10),(4,2,90),(4,3,50),(4,4,30),(4,5,50)) as d (usr,wk,pt)),
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.usr = w1.usr and w.wk = w1.wk+1
    left join n w2 on w.usr = w2.usr and w.wk = w2.wk+2
    left join n w3 on w.usr = w3.usr and w.wk = w3.wk+3
),
l as (
    select *, pt+x as total
    from sc
),
s as (
select usr, sum(total) total
from l
group by usr
)
select u.*,t.*
from s t
inner join u on u.usr = t.usr

如果您想查看所有细节更改,请在

中选择最终
select u.*,t.*
from l t
inner join u on u.usr = t.usr
数据库中的

应该是:

; 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