Hi @red ,
Please refer below query and check whether it is helpful. If not, please provide more sample data and expected output or more detailed rules.
drop table if exists FinalTable
drop table if exists UserActivity
--Final Table
CREATE TABLE dbo.FinalTable (
StoreNumber int NOT NULL,
StoreAmount MONEY NOT NULL,
StoreFlag INT NOT NULL
)
GO
--Insert data into the Final table
INSERT dbo.FinalTable (StoreNumber, StoreAmount, StoreFlag)
VALUES (101, '3000.00',2)
,(101, '4000.00',3)
,(101, '2000.00',1)
--Stage Table
CREATE TABLE dbo.UserActivity (
StoreNumber INT NOT NULL,
StoreAmount MONEY NOT NULL
)
GO
--Stage Table
INSERT dbo.UserActivity (StoreNumber, StoreAmount)
VALUES (101, '6000.00')
,(102, '1000.00')
;WITH CTE AS (
SELECT *
,ROW_NUMBER() OVER(PARTITION BY STORENUMBER ORDER BY (SELECT NULL) ) AS Row
from FinalTable)
,CTE2 AS (
SELECT T.STORENUMBER,T.StoreAmount,T.StoreFlag
FROM (
SELECT STORENUMBER, MAX(Row) as Max
FROM CTE
GROUP BY STORENUMBER) r
INNER JOIN CTE T
ON T.STORENUMBER=R.STORENUMBER AND T.Row=r.Max)
,CTE3 AS (
SELECT A.StoreNumber,A.StoreAmount NOWStoreAmount,B.StoreAmount PREStoreAmount
FROM UserActivity A INNER JOIN CTE2 B ON A.StoreNumber=B.StoreNumber)
INSERT dbo.FinalTable (StoreNumber, StoreAmount, StoreFlag)
SELECT StoreNumber,NOWStoreAmount,
CASE WHEN NOWStoreAmount>PREStoreAmount THEN 3
WHEN NOWStoreAmount<PREStoreAmount THEN 1 END
FROM CTE3
INSERT dbo.FinalTable (StoreNumber, StoreAmount, StoreFlag)
SELECT StoreNumber, StoreAmount,2
FROM UserActivity A
WHERE NOT EXISTS
( SELECT 1
FROM FinalTable B
WHERE A.StoreNumber=B.StoreNumber
);
select * from FinalTable
Output:
StoreNumber StoreAmount StoreFlag
101 3000.00 2
101 4000.00 3
101 2000.00 1
101 6000.00 3
102 1000.00 2
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hot issues October--Users always get connection timeout problem when using multi subnet AG via listener. Especially after failover to another subnet