T-SQL 在 SQL 服务器中另一个 table 的两个值之间使用 case 语句更新列

T-SQL update column with case statement when between two values from another table in SQL Server

我有两个表,我想在 Table2StartDayEndDay 之间更新 Table1 中的 Possession 列。

表 1

CompanyId Day GroupId Possession
99 1 1 0
99 1 2 0
99 2 1 0
99 2 2 0
99 3 1 0
99 3 2 0
99 4 1 0
99 4 2 0
99 5 1 0
99 5 2 0
99 6 1 0
99 6 2 0
99 7 1 0
99 7 2 0
99 8 1 0
99 8 2 0
99 9 1 0
99 9 2 0
99 10 1 0
99 10 2 0

表2

CompanyId GroupId StartDay EndDay
99 1 1 3
99 2 4 5
99 1 6 7
99 2 8 10

这是我写的更新语句,但 Table1 只更新 Table2 的第一行。我需要它更新 Table2.

的每一行
UPDATE Table1
SET Table1.Possession = 
    CASE 
        WHEN a.Day BETWEEN b.StartDay AND b.EndDay
             AND a.GroupId = b.GroupId 
        THEN 1
        ELSE 0
    END
FROM Table1 a
INNER JOIN Table2 b ON a.CompanyId = b.CompanyId

这是我想要的结果

CompanyId Day GroupId Possession
99 1 1 1
99 1 2 0
99 2 1 1
99 2 2 0
99 3 1 1
99 3 2 0
99 4 1 0
99 4 2 1
99 5 1 0
99 5 2 1
99 6 1 1
99 6 2 0
99 7 1 1
99 7 2 0
99 8 1 0
99 8 2 1
99 9 1 0
99 9 2 1
99 10 1 0
99 10 2 1

您的连接条件不正确,a 的每一行都与 b 的每一行匹配,因此您要更新 a 的每一行 4 次,其中 1 次应该使用 4?

您可以使用包含所有条件的外部联接,但最好使用 exists

编写
Update a 
 set a.possession=
 case when exists (
    select * from table2 b 
    where b.CompanyId=a.companyId 
      and b.groupId=a.groupId 
      and a.day between b.startday and b.endday
) then 1 else 0 end
from 
table1 a;