Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

sql - Inserting a new row of data into a table based on condition that compares with another table

I have a tracker table that tracks a certain number associated with our customers called "Tracker". The table looks like this:

customer_id    value     date_of_value
11111            2          2020-12-14
23332            6          2021-01-15

This table takes this information from another table called "Values", which is the exact same table as above but without the date_of_value column. This table keeps getting updated daily, and the Value associated with the customer gets overwritten with new values. What I would like to be able to do is to create a small job so the "Tracker" table looks at the "Values" table to see whether the value was updated. If so, I would like to insert a new row into the "Tracker" table with the customer's ID, the new value, and the date the value changed. In my mind, the query would look something like this:

CASE WHEN Tracker.value != Values.value
   THEN INSERT INTO Tracker (customer_id, value, date_of_value)
   VALUES (Values.id, values.value, GETDATE())

I tried using this along with UPDATE statement but none of them worked. Ideally, the "Tracker" table will look like this:

customerr_id    value      date_of_value
11111             2           2020-12-14
2332              6           2021-01-15
11111             3           2021-01-22
2332              8           2021-01-24 

How can I set up this query such that when I create a job, a new row is inserted with the updated information? When I tried using the UPDATE method, it overwrote the information in the "Tracker" table.

question from:https://stackoverflow.com/questions/65890904/inserting-a-new-row-of-data-into-a-table-based-on-condition-that-compares-with-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hmmm . . . You want the most recent value from the tracker table. Then compare that to the existing values and insert where there are differences:

INSERT INTO Tracker (customer_id, value, date_of_value)
    SELECT v.customer_id, v.value, GETDATE()
    FROM (SELECT v.*,
                 ROW_NUMBER() OVER (PARTITION BY v.customer_id ORDER BY v.value DESC) as seqnum
          FROM values v
         ) v LEFT JOIN
         Tracker t
         ON v.customer_id = t.customer_id AND
            v.value = t.value
    WHERE v.seqnum = 1 AND t.customer_id IS NULL;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...