In SQL Server, I have tables TAB
and STG
as follows:
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
)
I need to either
if stg_client/stg_security doesn't exist in the Tab table, insert the stg_Client/stg_Security data from Stg table to Tab table
if stg_client/stg_security exist in the Tab table:
update the Tab table's tab_Quantity with the sum of Tab.tab_Quantity & Stg.stg_Quantity
update the Tab table's tab_Cost with the sum of Tab.tab_Cost & Stg.stg_Cost
How can I do that ?
TAB table
Client Security Quantity Cost
-------------------------------------
JP L1 1 100
JP L2 2 200
JP L3 3 300
STG table
Client Security Quantity Cost
-------------------------------------
JP L1 10 1000
JP L3 30 3000
JP L4 40 4000
Desired result:
TAB table
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
The MERGE works
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);
Thank you.
you could use a join in updated
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
Another correct way to do this with SQL is with a LEFT OUTER JOIN for inserting the missing rows and an INNER JOIN for updating the existing rows -
Tip: Either Update matching before inserting missing or only insert the client/security fields in the insert statement to avoid updating the qty and cost of the newly inserted rows...
Here's a snippet:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.