Note that there are some explanatory texts on larger screens.

plurals
  1. POTSQL Compare 2 select's result and return result with most recent date
    primarykey
    data
    text
    <p>Wonder if someone could give me a quick hand. I have 2 select queries (as shown below) and I want to compare the results of both and only return the result that has the most recent date.</p> <p>So say I have the following 2 results from the queries:-</p> <pre><code>--------- ---------- ----------------------- --------------- ------ -- COMPANY A EMPLOYEE A 2007-10-16 17:10:21.000 E-mail 6D29D6D5 SYSTEM 1 COMPANY A EMPLOYEE A 2007-10-15 17:10:21.000 E-mail 6D29D6D5 SYSTEM 1 </code></pre> <p>I only want to return the result with the latest date (so the first one). I thought about putting the results into a temporary table and then querying that but just wondering if there's a simpler, more efficient way?</p> <pre><code>SELECT * FROM ( SELECT fc.accountidname, fc.owneridname, fap.actualend, fap.activitytypecodename, fap.createdby, fap.createdbyname, ROW_NUMBER() OVER (PARTITION BY fc.accountidname ORDER BY fap.actualend DESC) AS RN FROM FilteredContact fc INNER JOIN FilteredActivityPointer fap ON fc.parentcustomerid = fap.regardingobjectid WHERE fc.statecodename = 'Active' AND fap.ownerid = '0F995BDC' AND fap.createdon &lt; getdate() ) tmp WHERE RN = 1 SELECT * FROM ( SELECT fa.name, fa.owneridname, fa.new_technicalaccountmanageridname, fa.new_customerid, fa.new_riskstatusname, fa.new_numberofopencases, fa.new_numberofurgentopencases, fap.actualend, fap.activitytypecodename, fap.createdby, fap.createdbyname, ROW_NUMBER() OVER (PARTITION BY fa.name ORDER BY fap.actualend DESC) AS RN FROM FilteredAccount fa INNER JOIN FilteredActivityPointer fap ON fa.accountid = fap.regardingobjectid WHERE fa.statecodename = 'Active' AND fap.ownerid = '0F995BDC' AND fap.createdon &lt; getdate() ) tmp2 WHERE RN = 1 </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. 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