【问题标题】:Sql server map action to state to get the right resultSql server 将动作映射到状态以获得正确的结果
【发布时间】:2021-10-15 08:26:38
【问题描述】:

对于数据库,我需要从不同表的操作中记录状态。

表 1

ID Action
1 Accept
2 Save
3 Withdraw
4 Accept

表 2

ID State
1
2
3
4

结果
表2

ID State
1 Accepted
2 Draft
3 Withdrawn
4 Accepted

我正在考虑使用 CASE WHEN 查询来解决这个问题:

Update table 2
set state = action
from (select 
       case when action == Accept then Accepted
            when action == save then draft
            when action == withdraw then withdrawn
        end
      from table 1
)

我想知道这是否是最好的方法,或者是否可以为此使用某种映射器。

【问题讨论】:

    标签: sql sql-server case


    【解决方案1】:

    理想情况下,您应该维护某种联结表,将Table1 中的操作映射到Table2 中的状态。考虑:

    表2

    ID State
    1 Accepted
    2 Draft
    3 Withdrawn
    UPDATE t2
    SET State = t12.State
    FROM Table2 t2
    INNER JOIN Table12 t12
        ON t12.ID = t2.ID;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多