根据某些特定条件向字段添加数字

时间:2013-10-15 08:28:07

标签: tsql

我有以下数据

CompId PersonelNo EduId RecordsDay DateEs
 1      1000        1       2       1370
 1      1000        2       10      1370
 1      1002        2       5       1380
 1      1003        1       4       1391
 1      1003        2       7       1391

我想为MaximumDdud的RecordsDay添加(1392-1390 = 2)并记录哪些DateE小于或等于1390,并为RecordsDay添加(DateEs -1390)最大EduID和DateE大于1390的记录

所以数据就像这样

 CompId PersonelNo EduId RecordsDay DateEs
  1      1000        1       2       1370 // record is the same becuase eduID is not Max for this Personel
  1      1000        2       12      1370 // this is max EduId for this personel and DateEs is less than 1390 so (1392-1390) +10 = 12
  1      1002        2       7       1380 //this is the only record for this personel and DateEs is less than 1390(1392-1390) +5 = 7
  1      1003        1       4       1391 // record is the same becuase eduID is not Max for this Personel
  1      1003        2       8       1391 // this is max EduId for this personel and DateEs is Greater than 1390 so (1391-1390) +7 = 8

我想拥有TSQl。我正在努力,但可以写到现在

1 个答案:

答案 0 :(得分:1)

您可以尝试:

SELECT CASE 
    WHEN [EduId] = MAX(EduId) OVER (Partition by PersonelNo) AND DateEs <= 1390 THEN RecordsDay + 2 
    WHEN [EduId] = MAX(EduId) OVER (Partition by PersonelNo) AND DateEs > 1390 THEN RecordsDay + (DateEs -1390) END