[英]If value of 1 table exists in the 2nd table, update the 2nd table value with sum of 1st and 2nd tables, else insert 1st table data to 2nd table
在 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 表
如果 stg_client/stg_security 存在於 Tab 表中:
用 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);
謝謝你。
你可以在更新中使用加入
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
使用 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.