Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL SERVER - Tricky Select Statement
    primarykey
    data
    text
    <p>Trying to rack my brain for a while, lots of Googling, but to no avail. I have a data set that has the following fields I need to query: <code>DEPT,NUM,TERM,ITLE</code>. I have the following possible rows.</p> <pre><code>DEPT--NUM---TERM------TITLE OSS - 1550 - 200830 - COURSE NAME (CI) OSS - 1550 - 200930 - COURSE NAME (CI) OSS - 1550 - 201230 - COURSE NAME ENG - 1600 - 200930 - OTHER COURSE (CI) OSS - 1600 - 200830 - ANOTHER COURSE (CI) USS - 2500 - 201240 - COURSE (CI) PSY - 1600 - 200830 - COURSE TITLE </code></pre> <p>What I need to do is query a table with data such as this and then pull the <code>DEPT/NUM</code> (OSS 1550) where the title matches a query ONLY IF it's the latest title. </p> <p>So if I do a search for (CI) I want 3 results using the set above (ENG 1600, OSS 1600, ISS 2500), because 201230 is the latest entry for OSS 1550 I don't want that one, but I do want the others. Right now I cannot for the life of me figure out how to write a query that will do that.</p> <p>Any help would be appreciated. Let me know if I am not clear enough.</p> <p>EDIT</p> <p>I am only getting a single record, here is what I am using based on what you have said SELECT data.* FROM ( SELECT SCBCRSE_SUBJ_CODE || ' ' || SCBCRSE_CRSE_NUMB AS crs_combo, SCBCRSE_TITLE as title, row_number() over (ORDER BY SCBCRSE_EFF_TERM DESC, SCBCRSE_CRSE_NUMB DESC) as term FROM SCBCRSE WHERE (SCBCRSE_TITLE LIKE '%' || :srch || '%') ) data WHERE data.term = 1</p> <p>My formatting is now working... no idea why I have four spaces.</p> <p>EDIT AGAIN I guess I didn't provide enough sample data... see edited table above. I need the three records with unique DEPT/NUM and the CI in the title, but not the one with older titles and CI. Make sense.</p> <p>Sorry for not being clear.</p> <p>ANSWER... here is the winner.</p> <pre><code>SELECT data.* FROM ( SELECT SCBCRSE_SUBJ_CODE || ' ' || SCBCRSE_CRSE_NUMB AS crs_combo, SCBCRSE_TITLE as title, row_number() over (partition by SCBCRSE_SUBJ_CODE,SCBCRSE_CRSE_NUMB ORDER BY SCBCRSE_EFF_TERM DESC) as seqnum FROM SCBCRSE ) data WHERE seqnum = 1 AND title LIKE '%' || :srch || '%' </code></pre> <p>Thanks for your help everyone. I wasted hours on this and you answered it in minuets.</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