簡體   English   中英

當 SQL 服務器中另一個表的兩個值之間時,T-SQL 使用 case 語句更新列

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

我有兩個表,我想更新Table1中的Possession列,當日期介於Table2StartDayEndDay之間時。

表格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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM