如果第2个表中存在1个表的值,则使用第1个表和第2个表的总和更新第2个表值,否则将第1个表数据插入第2个表

问题描述 投票:-1回答:2

在SQL Server中,我有表TABSTG如下:

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
)

我需要

  1. 如果Tab表中不存在stg_client / stg_security,则将stg_Client / stg_Security数据从Stg表插入到Tab表中
  2. 如果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);

谢谢。

sql sql-server tsql
2个回答
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 

0
投票

使用SQL执行此操作的另一种正确方法是使用LEFT OUTER JOIN插入缺少的行,使用INNER JOIN更新现有行 -

提示:在插入缺失之前更新匹配或仅在insert语句中插入客户端/安全性字段,以避免更新新插入的行的数量和成本...

这是一个片段:

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)

© www.soinside.com 2019 - 2024. All rights reserved.