我的数据库表中有3列,并希望在SQL中实现以下目标
Create table #TempTableChild
(
Child_Id int,
UnReadCount int,
Adult_id int
)
我在#TempTableChild
中具有以下值:
Child_Id | UnreadCount | AdultId | NewColumnVal
---------+-------------+---------+----------------
28 | 1 | 4 | 0
29 | 1 | 4 | 0
28 | 0 | 5 | 0
29 | 0 | 5 | 0
5 | 1 | 6 | 0
6 | 0 | 8 | 0
而且,要获得以下数据。
Child_Id | UnreadCount | AdultId | NewColumnVal
---------+-------------+---------+----------------
28 | 1 | 4 | 1
29 | 1 | 4 | 0
28 | 0 | 5 | 0
29 | 0 | 5 | 0
5 | 1 | 6 | 1
6 | 0 | 8 | 0
如上所示,对于每个不同的AdultId,我希望NewColumnVal的最大值为1。
仅当第一个Child_Id的AdultId = 4 UnreadCount = 1 NewColumnVal =1
时,然后所有其他后续值NewColumnVal = 0,然后如果UnreadCount = 0,则再次获取新的Adult_id最高值NewColumnVal = 0
答案 0 :(得分:2)
您可以将窗口函数与Case Statement一起使用。见下文:
CREATE TABLE t ( Child_Id INT, UnreadCount INT, AdultId INT, NewColumnVal INT ); INSERT INTO t (Child_Id, UnreadCount, AdultId, NewColumnVal) VALUES ('28', '1', '4', '0'), ('29', '1', '4', '0'), ('28', '0', '5', '0'), ('29', '0', '5', '0'), ('5', '1', '6', '0'), ('6', '0', '8', '0'); GO
6 rows affected
select Child_Id, UnreadCount, AdultId, CASE WHEN UnreadCount > 0 AND rn = 1 THEN 1 ELSE 0 END NewColumnVal from ( select *, row_number() over (partition by AdultId order by Child_Id ) rn from t ) tou GO
Child_Id | UnreadCount | AdultId | NewColumnVal -------: | ----------: | ------: | -----------: 28 | 1 | 4 | 1 29 | 1 | 4 | 0 28 | 0 | 5 | 0 29 | 0 | 5 | 0 5 | 1 | 6 | 1 6 | 0 | 8 | 0
db <>提琴here