我正在处理一个未规范化的数据库,由于我没有权限,因此无法规范化。问题是
我有两张桌子
表的结构类似于
Gl_Account(空表或旧数据)
loc | gl_acct | HMISTOTAL
-------------------------------
| |
-------------------------------
试算平衡
loc | g1101 | g1102 | g1103
----------------------------------------
1400 | 20 | 30 | 0
----------------------------------------
1500 | 10 | 0 | 40
----------------------------------------
现在我想做的是
从 trialBalance 表中获取不在 Gl_Account 表中的记录,其中包含相应的GL_acct编号,其中 gXXXX 下的金额(在试算表中)不是零
让我用一个例子解释一下。记住上面的表我想填写表GL_Account为
GL_Account
loc | gl_acct | HMISTOTAL
---------------------------------------
1400 | 1101 | 20
---------------------------------------
1400 | 1102 | 30
---------------------------------------
1500 | 1101 | 10
---------------------------------------
1500 | 1103 | 40
---------------------------------------
我已经尝试过这个查询,但只有捕获的第一条记录被输入到gl_accountt表中。我现在跳过了金额部分..但这是必需的。
insert into Gl_Account (loc,gl_acct,HMISTOTAL)
select * from (
select a.loc,
CASE
WHEN a.G1101 <> 0 THEN '1101'
WHEN a.G1102 <> 0 THEN '1102'
WHEN a.G1104 <> 0 THEN '1104'
WHEN a.G1151 <> 0 THEN '1151'
END AS gl_Acct
'0' as HMISTOTAL
FROM trialBalance a where NOT EXISTS
(SELECT 1 from GL_Account b WHERE b.loc = a.loc)) ab
提前感谢。
答案 0 :(得分:1)
试试这个。
INSERT INTO Gl_Account (loc,gl_acct,HMISTOTAL)
SELECT * FROM (
SELECT trialBalance .loc,
CASE
WHEN a.G1101 <> 0 THEN '1101'
WHEN a.G1102 <> 0 THEN '1102'
WHEN a.G1104 <> 0 THEN '1104'
WHEN a.G1151 <> 0 THEN '1151'
END AS gl_Acct
'0' AS HMISTOTAL
FROM
trialBalance LEFT JOIN GL_Account
ON trialBalance.loc = GL_Account.loc
WHERE
GL_Account.loc IS NULL
)
答案 1 :(得分:1)
这将获得您指定的结果:
SELECT loc,
gl_acct,
CASE gl_acct
WHEN '1101' THEN g1101
WHEN '1102' THEN g1102
WHEN '1103' THEN g1103
END AS HMISTOTAL
FROM trialBalance a
JOIN (
VALUES ('1101'),
('1102'),
('1103')
) c(gl_acct) ON
(a.g1101 <> 0 AND gl_acct = '1101') OR
(a.g1102 <> 0 AND gl_acct = '1102') OR
(a.g1103 <> 0 AND gl_acct = '1103')
WHERE NOT EXISTS
(
SELECT 1
FROM GL_Account x
WHERE x.loc = a.loc
)
我使用了VALUES
行构造函数来创建一个包含要加入的值的临时表。