Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do this:</p> <pre><code>;WITH CTE AS ( SELECT pih.PID, piv.TSV, piv.Variable_ID, piv.Value_ID, piv.Manual_Value, ROW_NUMBER() OVER (PARTITION BY piv.TSV ORDER BY pih.PID) rownum FROM Process_Instance_Value AS piv INNER JOIN Process_Instance_History AS pih ON piv.PID = pih.PID WHERE piv.Variable_ID IN ( SELECT Variable_ID FROM someTable WHERE Transition_ID = @someValue) AND piv.PID = @someValue ) SELECT * FROM CTE WHERE rownum = 1; </code></pre> <p><strong>Note that:</strong> This will return the minimum <code>pih.PID</code> for each distinct <code>piv.TSV</code> if you want the max, just use <code>ORDER BY pih.PID DESC</code> instead.</p> <p><strong>How does this work:</strong></p> <p>The ranking function <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="nofollow"><strong><code>ROW_NUMBER() OVER()</code></strong></a> will give a ranking number for each group that has the same column listed in the <code>PARTITION BY</code>, in our case <code>piv.TSV</code>, this ranking number will be ordered, for each group, according to the <code>ORDER BY</code> clause defined inside the <code>OVER</code> clause, in our case <code>ORDER BY pih.PID</code>. I used a <a href="http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx" rel="nofollow"><strong>CTE</strong></a> instead of using subquery.</p> <p>Then the I used <code>WHERE rownum = 1</code>, since the ranking number <code>rownum</code> was given for each group of records that has the same <code>piv.TSV</code> ranked in descendent order, then the record with <code>rownum = 1</code> will be the record with the minimum <code>pih.PID</code>(think about it).</p> <p>You can however, get the same result using an inner join with a <code>GROUP BY</code> like so:</p> <pre><code> SELECT pih.PID, piv.TSV, piv.Variable_ID, piv.Value_ID, piv.Manual_Value FROM Process_Instance_Value AS piv INNER JOIN ( SELECT TSV, MIN(PID) MinPID FROM Process_Instance_Value GROUP BY TSV ) piv2 ON piv.PID = piv2.MinPID INNER JOIN Process_Instance_History AS pih ON piv.PID = pih.PID WHERE piv.Variable_ID IN ( SELECT Variable_ID FROM someTable WHERE Transition_ID = @someValue) AND piv.PID = @someValue </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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