在SQL Server中,我有如下表TAB
和STG
:
CREATE TABLE [Tab]
(
[tab_Client] [VARCHAR](30) NULL,
[tab_Security] [VARCHAR](30) NULL,
[tab_Quantity] [FLOAT] NULL,
[tab_Cost] [FLOAT] NULL
)
CREATE TABLE [Stg]
(
[stg_client] [VARCHAR](30) NULL,
[stg_security] [VARCHAR](30) NULL,
[stg_Quantity] [FLOAT] NULL,
[stg_Cost] [FLOAT] NULL
)
我需要
如果Tab表中不存在stg_client / stg_security,则将Stg_Client / stg_Security数据从Stg表插入到Tab表中
如果Tab表中存在stg_client / stg_security:
使用Tab.tab_Quantity和Stg.stg_Quantity的总和更新Tab表的tab_Quantity
使用Tab.tab_Cost和Stg.stg_Cost的总和更新Tab表的tab_Cost
我该怎么做?
TAB表
Client Security Quantity Cost
-------------------------------------
JP L1 1 100
JP L2 2 200
JP L3 3 300
STG表
Client Security Quantity Cost
-------------------------------------
JP L1 10 1000
JP L3 30 3000
JP L4 40 4000
所需结果:
TAB表
Client Security Quantity Cost
-----------------------------------------
JP L1 11 1100 -> Sum of Tab and Stg table
JP L2 2 200
JP L3 33 3300 -> Sum of Tab and Stg table
JP L4 40 4000 -> From Stg table
MERGE有效
MERGE TAB AS target
USING STG AS source ON target.tab_client = source.stg_client
AND target.tab_security = source.stg_security
WHEN MATCHED THEN
UPDATE
SET target.tab_quantity = source.stg_quantity + target.tab_quantity,
target.tab_cost = source.stg_cost + target.tab_cost
WHEN NOT MATCHED BY target THEN
INSERT (tab_client, tab_security, tab_quantity, tab_cost)
VALUES (source.stg_client, source.stg_security, source.stg_quantity, source.stg_cost);
谢谢。
答案 0 :(得分:0)
您可以在更新中使用
update TAB
set TAB.cost = TAB.cost + STG.cost ,
TAB.Quantity = TAB.Quantity + STG.Quantity
from TAB
INNER JOIN STG ON TAB.clinet = STG.client
AND TAB.security = STG.security
答案 1 :(得分:0)
使用SQL进行此操作的另一种正确方法是使用LEFT OUTER JOIN来插入缺少的行,而使用INNER JOIN来更新现有行-
提示:在插入缺失项之前更新匹配项,或者仅在插入语句中插入客户/安全字段,以避免更新新插入的行的数量和成本...
这是一个片段:
UPDATE t
SET tab_Cost = t.tab_Cost + s.stg_Cost ,
tab_Quantity = t.tab_Quantity + s.stg_Quantity
FROM TAB t
INNER JOIN STG s ON t.clinet = s.client AND t.security = s.security
INSERT INTO TAB (tab_client, tab_security, tab_quantity, tab_cost)
SELECT s.stg_Client, s.stg_Security, s.quantity, s.Cost
FROM STG s LEFT OUTER JOIN
TAB t ON t.clinet = s.client
AND t.security = s.security
WHERE t.tab_client IS NULL```
(assuming tab_client is a non nullable field)