Note that there are some explanatory texts on larger screens.

plurals
  1. PORepeating Subquery in DB2 update
    primarykey
    data
    text
    <p>I am currently creating an update statement which will update a bitemporal table. It does the following:</p> <p>Update every Row for every ID and set the RELATION_ID to the RELATION_ID of the newest row.</p> <p>In this query, there is a repeating subquery ( Because I first use it to get the value used to update) and also ( I don't want to update rows which already have this RELATION_ID)</p> <p>Is there a way to reuse the value from the first query or any alternatives?(Without programming, pure SQL required)</p> <pre><code>UPDATE TBL_CLIENT UPD SET RELATION_ID = ( SELECT RELATION_ID FROM TBL_CLIENT SUBQ WHERE UPD.ID = SUBQ.ID AND UPDATE_TIMESTAMP = ( SELECT MAX(UPDATE_TIMESTAMP) FROM TBL_CLIENT SUBSQ WHERE SUBSQ.ID = SUBQ.ID ) ) WHERE ID IN ( SELECT ID FROM TBL_CLIENT QU GROUP BY ID HAVING COUNT(DISTINCT(RELATION_ID)) &gt; 1 ) AND RELATION_ID &lt;&gt; ( SELECT RELATION_ID FROM TBL_CLIENT SUBQ2 WHERE UPD.ID = SUBQ2.ID AND UPDATE_TIMESTAMP = ( -- Update mit STID des neusten Eintrages SELECT MAX(UPDATE_TIMESTAMP) FROM TBL_CLIENT SUBSQ2 WHERE SUBSQ2.ID = SUBQ2.ID ) ) </code></pre> <p>Example:</p> <p>ID / RELATION_ID / UPDATE_TIMESTAMP </p> <ul> <li>1 / 10 / 1.1.2000</li> <li>1 / 12 / 5.1.2002 </li> <li>1 / 15 / 28.3.2008</li> </ul> <p>After Update:</p> <ul> <li>1 / 15 / 1.1.2000</li> <li>1 / 15 / 5.1.2002</li> <li>1 / 15 / 28.3.2008 </li> </ul> <p>The last row was the most recent row, therefore it's relation id was taken (and the row itself wasn't updated!, important for an other part of the query which isn't included here)</p> <p>Thanks for any recommendations</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload