2013-10-15 34 views
1

我有以下數據根據一些特定條件添加編號,以一個字段

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 

我要添加(1392年至1390年= 2)的最大EduID和記錄的RecordsDay其中DateEs小於或等於1390,並添加(DateEs -1390)爲RecordsDay最大EduID和記錄與DateEs比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

你可以試試:

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 
相關問題