我有三个以这种格式构建的表:
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 |
...
我希望使用基于表Type#
的{{1}}列的条件更新表@A
中的Type
列。这是我尝试使用的SQL查询:
@C
而不是获得预期值:
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
列TypeName
的列没有正确更新?为什么我会修复它以便我可以获得预期值?
答案 0 :(得分:3)
问题是你每人都有几行@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
现在无法测试,但你甚至可以在那里制作文字,如下所示:
max时的情况(案例类型1时1其他0)= 1然后'是'否则'否' 结束为Type1
您可以在更新中将其用作派生表,也可以先将结果收集到另一个表变量
中