![](/img/trans.png)
[英]How to update a record by checking a value in another record in same table
[英]How to Set a Record Value equal to Another Record Value in the Same Table
我正在嘗試使用同一列中已有的值更新表中的列。 該表有許多記錄,但它們可能與 ID 列中的一兩個其他記錄共享一些值。 假設在 ID 列中有兩條 ID 值相同的記錄。 然后我想更新另一個名為 Details 的列。 具有相同 ID 的兩條記錄沒有相同的詳細信息值。 一個在該列中有一個 integer,另一個有一個 Null。 我的問題是,對於包含相同 ID 的每組記錄,如何將 Null 替換為 integer。 下面我將列出一個示例。
ID | 細節 |
---|---|
1234 | 55.60 |
1567 | 85.40 |
1234 | Null |
4569 | 58.09 |
1567 | Null |
8965 | 77.90 |
我想要一個基於 ID 填充這些空值的查詢。
ID | 細節 |
---|---|
1234 | 55.60 |
1567 | 85.40 |
1234 | 55.60 |
4569 | 58.09 |
1567 | 85.40 |
8965 | 77.90 |
我正在使用的表格實際上要大得多,並且有更多的列。 這是我認為與我正在嘗試做的事情相關的兩個。 我已經嘗試過自我加入,它似乎出錯了。 還有另一列通過填充“打開”或“關閉”來區分相同的 ID,如果這有幫助的話,我沒有包含在示例中。 這是在 SQL 服務器 2019 上。提前致謝。
考慮到只有兩個相同的 id 並且一個具有詳細價值:
update t1
set
t1.Details = t2.Details
from
tablename t1
join tablename t2
on t1.details is null
and t1.id = t2.id
and t2.details is not null
您可以在 SQL 服務器中使用可更新的 CTE 和 window 函數:
with toupdate as (
select t.*, max(details) over (partition by id) as max_details
from t
)
update toupdate
set details = max_details
where details is null and max_details is not null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.