问题是指T-SQL查询。
有两个表:
表-A:
A_ID | Category | SomeValue .
-----+----------+-----------.
0 | 1 | ... .
1 | 1 | ... .
2 | 2 | ... .
2 | 2 | ... .
应该由Table_A的Category条件填充的和 Table_B 。根据Table_A的类别,我想将一些数据写入第二个表的第1列或第2列。另一列应保持为空:
B_ID | cat_x | cat_y .
-----+----------+-----------.
0 | someval | null . //Category was 1
1 | null | someval . //Category was 2
2 | null | someval . //Category was 2
2 | someval | null . //Category was 1
我的输入是整张表。对于每一行,它必须查找要写入的目标列。
我尝试使用CASE,但我没有得到它。以下是一些可能有助于您理解的伪代码:
CASE
WHEN Category=1
THEN
INSERT INTO (B_ID,cat_x)
SELECT (someval) //ID could get filled automatically
FROM sometable
WHEN Category = 2
THEN
INSERT INTO (B_ID,cat_y)
SELECT (someval) //ID could get filled automatically
FROM sometable
END
我想我最大的问题是如何编写condition / when-clause的语法。
答案 0 :(得分:1)
不完全。 case
表达式应该是`select query:
INSERT INTO (B_ID, cat_x, cat_y)
SELECT (case when a.category = 1 then someval end),
(case when a.category = 2 then someval end)
FROM A
WHERE category IN (1, 2);