title: Select latest row on duplicate values while transfering table?
body: <p>I have a logging table that is live which saves my value to a table frequently. </p>
  
  <p>My plan is to take those values and put them on a temporary table with </p>
  
  <pre><code>SELECT * INTO #temp from Block 
  </code></pre>
  
  <p>From there I guess my block table is empty and the logger can keep on logging new values.</p>
  
  <p>The next step is that I want to save them in a existing table. I wanted to use </p>
  
  <pre><code>INSERT INTO TABLENAME(COLUMN1,COLUMN2...) SELECT (COLUMN1,COLUMN2...) FROM #temp
  </code></pre>
  
  <p>The problem is that the <code>#temp</code> table has duplicates primary keys. And I only want to store the last ID.</p>
  
  <p>I have tried <code>DISTINCT</code> but it didn't work. Could not get <code>ROW_Count</code> to work.  Are there any ideas on how I should do it? I wish to make it with as few reads as possible.</p>
  
  <p>Also, in the future I plan to send them to another database, how do I do that on SQL Server? I guess it's something like <code>FROM Table [in databes]</code>? </p>
  
  <p>I couldn't get the blocks to copy. But here goes:</p>
  
  <pre><code>create TABLE Product_log (
      Grade char(64),
      block_ID char(64) PRIMARY KEY NOT NULL,
      Density char(64), 
      BatchNumber char(64) NOT NULL,
      BlockDateID Datetime 
  );
  </code></pre>
  
  <p>That is my table i want to store the data in. There I do not wish to have duplicates on the id. The problem is, while logging I get duplicates since I log on change. Lets say that the batchid is 1, if it becomes 2 while logging. I will get a blockid twice, both with batch number 1 and 2. How do I pick the latter? </p>
  
  <p>Hope I explained enough for guidance. While logging they look like this: </p>
  
  <pre><code>id  SiemensTiaV15_s71200_BatchTester_NewBatchIDValue_VALUE  SiemensTiaV15_s71200_BatchTester_TestWriteValue_VALUE   SiemensTiaV15_s71200_BatchTester_TestWriteValue_TIMESTAMP   SiemensTiaV15_s71200_MainTank_Density_VALUE SiemensTiaV15_s71200_MainTank_Grade_VALUE
  1   00545                                                               S0047782                                                            2020-06-09 11:18:44.583 0                                                                   xxxxx    
  2   00545                                                               S0047783                                                            2020-06-09 11:18:45.800 0                                                                   xxxxx    
  </code></pre>