[英]T-SQL update column with case statement when between two values from another table in SQL Server
我有兩個表,我想更新Table1
中的Possession
列,當日期介於Table2
的StartDay
和EndDay
之間時。
表格1
公司編號 | 天 | 組 ID | 擁有 |
---|---|---|---|
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
公司編號 | 組 ID | 開始日 | 結束日 |
---|---|---|---|
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
這是我想要的結果
公司編號 | 天 | 組 ID | 擁有 |
---|---|---|---|
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 次,應該使用 4 中的哪 1 個?
您可以使用具有所有條件的外連接,但最好使用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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.