Update first table based on values from second table

Viewed 373

I have two tables:

- @CAMERC
- @CAMERC_LOG

I have to update column @CAMERC.MERC_LPR with values from column @CAMERC_LOG.MERC_LPR. Records must match on MERC_KEY, but only one record must be taken from @CAMERC_LOG - with highest MERC_KEY_LOG, and @CAMERC_LOG.MERC_LPR must not be null or 0.

My problem is updating one table based on results from second table. I don't know how to properly make such an update?

Table @CAMERC:

+----------+----------+
| MERC_KEY | MERC_LPR |
+----------+----------+
|        1 | 0.0000   |
|        2 | NULL     |
|        3 | 0.0000   |
|        4 | 0.0000   |
+----------+----------+

Table @CAMERC_LOG:

+----------+--------------+----------+
| MERC_KEY | MERC_KEY_LOG | MERC_LPR |
+----------+--------------+----------+
|        1 |            1 | 1.1000   |
|        1 |            2 | 2.3000   |
|        2 |            3 | 3.4000   |
|        2 |            4 | 4.4000   |
|        1 |            5 | 7.8000   |
|        1 |            6 | NULL     |
|        2 |            7 | 0.0000   |
|        2 |            8 | 12.4000  |
|        3 |            1 | 12.1000  |
|        3 |            2 | 42.3000  |
|        3 |            3 | 43.4000  |
|        3 |            4 | 884.4000 |
|        4 |            5 | 57.8000  |
|        4 |            6 | NULL     |
|        4 |            7 | 0.0000   |
|        4 |            8 | 412.4000 |
+----------+--------------+----------+

Code for table creation:

DECLARE @CAMERC TABLE
(
MERC_KEY INT,
MERC_LPR DECIMAL(10,4)
)

DECLARE @CAMERC_LOG TABLE
(
MERC_KEY INT,
MERC_KEY_LOG INT,
MERC_LPR DECIMAL(10,4)
)

INSERT INTO @CAMERC(MERC_LPR, MERC_KEY) VALUES(0, 1),(NULL,2),(0,3),(0,4)
INSERT INTO @CAMERC_LOG(MERC_LPR, MERC_KEY, MERC_KEY_LOG) VALUES(1.1, 1,1),(2.3,1,2),(3.4,2,3),(4.4,2,4),(7.8, 1,5),(NULL,1,6),(0,2,7),(12.4,2,8),
(12.1, 3,1),(42.3,3,2),(43.4,3,3),(884.4,3,4),(57.8, 4,5),(NULL,4,6),(0,4,7),(412.4,4,8)
1 Answers

Try this:

WITH DataSource AS 
(
    SELECT MERC_KEY
         ,ROW_NUMBER() OVER (PARTITION BY  MERC_KEY ORDER BY MERC_KEY_LOG DESC) AS [RowID]
         ,MERC_LPR
    FROM @CAMERC_LOG
    WHERE MERC_LPR IS NOT NULL
        AND MERC_LPR <> 0
)
UPDATE @CAMERC
SET MERC_LPR = B.[MERC_LPR]
FROM @CAMERC A
INNER JOIN DataSource B
    ON A.[MERC_KEY] = B.[MERC_KEY]
    AND B.[RowID] = 1

SELECT *
FROM @CAMERC

enter image description here

The idea is to eliminated the invalid records from the @CAMER_LOG and then using ROW_NUMBER to order the rows by MERC_KEY_LOG. After that, we are performing UPDATE by only where RowID = 1.

Related