将一列 table 的多列更新为另一列 table 的一列

Update multiple columns from one table with one column from another table

我有三个 table 以这种格式构建:

DECLARE @A
(
    TypeName varchar(100),
    Type1 varchar(3),
    Type2 varchar(3),
    Type3 varchar(3),
    Type4 varchar(3),
    Type5 varchar(3),
    Type6 varchar(3)
)

Data:
| Bob   | null | null | null | null | null | null |
| Steve | null | null | null | null | null | null |
| Bill  | null | null | null | null | null | null |
...

DECLARE @B
(
    NameID int,
    Name varchar(100)
)

Data:
| 1 | Bob |
| 2 | Steve |
| 3 | Bill |
...

DECLARE @C
(
    NameID int,
    Type int
)

Data:
| 1 | 1 |
| 1 | 3 |
| 2 | 1 |
| 3 | 2 |
...

我想使用基于 table @CType 列的条件更新 table @A 中的 Type# 列.这是我尝试使用的 SQL 查询:

UPDATE @A SET
    Type1 = (CASE WHEN c.Type = 6 THEN 'Yes' ELSE 'No' END),
    Type2 = (CASE WHEN c.Type = 1 THEN 'Yes' ELSE 'No' END),
    Type3 = (CASE WHEN c.Type = 2 THEN 'Yes' ELSE 'No' END),
    Type4 = (CASE WHEN c.Type = 3 THEN 'Yes' ELSE 'No' END),
    Type5 = (CASE WHEN c.Type = 4 THEN 'Yes' ELSE 'No' END),
    Type6 = (CASE WHEN c.Type = 5 THEN 'Yes' ELSE 'No' END),
FROM @A
    INNER JOIN @B b ON b.Name = TypeName
    INNER JOIN @C c ON c.NameID = b.NameID

SELECT * FROM @A

而不是获得期望值:

| Bob   | No | Yes | No  | Yes | No | No | <-- Correct
| Steve | No | Yes | No  | No  | No | No |
| Bill  | No | No  | Yes | No  | No | No |

我得到这些值:

| Bob   | No | Yes | No  | No  | No | No | <-- Incorrect (noticed the third column from the right being set to No instead of Yes)
| Steve | No | Yes | No  | No  | No | No |
| Bill  | No | No  | Yes | No  | No | No |

我也试过将语句重写成这样:

UPDATE @A SET
    Type1 = (CASE WHEN t.Type = 6 THEN 'Yes' ELSE 'No' END),
    Type2 = (CASE WHEN t.Type = 1 THEN 'Yes' ELSE 'No' END),
    Type3 = (CASE WHEN t.Type = 2 THEN 'Yes' ELSE 'No' END),
    Type4 = (CASE WHEN t.Type = 3 THEN 'Yes' ELSE 'No' END),
    Type5 = (CASE WHEN t.Type = 4 THEN 'Yes' ELSE 'No' END),
    Type6 = (CASE WHEN t.Type = 5 THEN 'Yes' ELSE 'No' END),
FROM
(
    SELECT b.Name, c.Type
    FROM @C c
        INNER JOIN @B b on b.NameID = c.NameID
) t
WHERE t.Name = TypeName

但还是返回了后面的结果

那么,为什么 TypeNameBob 的列未正确更新,我该如何解决才能获得我的预期值?

问题是每个人在@C 中有几行。您必须先将其设为一行才能更新数据:

select
  NameID,
  max(case Type when 1 then 1 else 0 end) as Type1,
  max(case Type when 2 then 1 else 0 end) as Type2,
  max(case Type when 3 then 1 else 0 end) as Type3,
  max(case Type when 4 then 1 else 0 end) as Type4,
  max(case Type when 5 then 1 else 0 end) as Type5,
  max(case Type when 6 then 1 else 0 end) as Type6
from
  @C
group by
  NameID

现在无法对此进行测试,但您甚至可以在此处制作文本,使用如下内容:

case when max(case Type when 1 the 1 else 0) = 1 then 'Yes' else 'No' end as Type1

您可以在更新中将其用作派生 table,或者先将结果收集到另一个 table 变量