Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Below is a version that <strike>only gets the <code>max</code> once and </strike> should remove the correlated sub-queries. It does still use sub-queries, but, as they're in the <code>FROM</code> clause rather than the <code>SELECT</code> clause, the database should do a better job of resolving them. It's probably possible to remove those sub-queries as well, but it's more readable this way. This version also uses the SQL-99 syntax for joins, which is generally considered preferable.</p> <pre><code>SELECT table_4.incident_type, table_4.poc_contact, t2.sum_of_shortage, t3.help_notes, table_4.report_num FROM table_4 LEFT JOIN (SELECT table_2.rec_id, table_2.note_date || ' ' || table_1.user_first_name || ' ' || table_1.user_last_name || ' : ' || table_2.other_help_notes AS sum_of_shortage FROM table_1 JOIN table_2 ON table_2.user_id = table_1.user_id WHERE table_2.note_date = (SELECT MAX(table_2.note_date) AS max_date FROM table_2 WHERE table_2.rec_id = table_4.rec_id AND table_2.note_date &lt;= table_4.report_date)) t2 ON t2.rec_id = table_4.rec_id LEFT JOIN (SELECT table_3.rec_id, table_3.note_date || ' ' || table_1.user_first_name || ' ' || table_1.user_last_name || ' : ' || table_3.other_help_notes AS help_notes FROM table_1 JOIN table_3 ON table_3.user_id = table_1.user_id WHERE table_2.note_date = (SELECT MAX(table_3.note_date) AS max_date FROM table_3 WHERE table_3.rec_id = table_4.rec_id AND table_3.note_date &lt;= table_4.report_date)) t3 ON t3.rec_id = table_4.rec_id WHERE table_4.site_id = '1'; </code></pre> <hr> <p>@shawno: You're right, the <code>with</code> clause was flawed because I misread your initial query. Above is a corrected version. Because the <code>max</code> values are specific to each row, the method that you were already using to get those values is probably the most efficient. Your best option for optimizing this appears to just be moving the sub-queries from the <code>select</code> clause to the <code>from</code> clause.</p> <p>Also, this is an untested solution, as I have neither your table structure nor your data. The best I can do without putting far too much work into it is to verified that the syntax is valid.</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.
    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.
 

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