Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since you are using SQL Server 2005, you can use the new (CROSS|OUTTER) APPLY clause. The APPLY clause let's you join a table with a table valued function.</p> <p>To solve the problem, first define a table valued function to retrieve the top n rows from Thing for a specific id, date ordered:</p> <pre><code>CREATE FUNCTION dbo.fn_GetTopThings(@ThingID AS GUID, @n AS INT) RETURNS TABLE AS RETURN SELECT TOP(@n) * FROM Things WHERE ThingID= @ThingID ORDER BY PriceDateTime DESC GO </code></pre> <p>and then use the function to retrieve the top 1 records in a query:</p> <pre><code>SELECT * FROM Thing t CROSS APPLY dbo.fn_GetTopThings(t.ThingID, 1) WHERE t.ThingID IN (1,2,3,4,5,6) </code></pre> <p>The magic here is done by the APPLY clause which <strong>applies the function to every row in the left result set</strong> then joins with the result set returned by the function then retuns the final result set. (Note: to do a left join like apply, use OUTTER APPLY which returns all rows from the left side, while CROSS APPLY returns only the rows that have a match in the right side)</p> <p>BlaM: Because I can't post comments yet( due to low rept points) not even to my own answers ^^, I'll answer in the body of the message: -the APPLY clause even, if it uses table valued functions it is optimized internally by SQL Server in such a way that it doesn't call the function for every row in the left result set, but instead takes the inner sql from the function and converts it into a join clause with the rest of the query, so the performance is equivalent or even better (if the plan is chosen right by sql server and further optimizations can be done) than the performance of a query using subqueries), and in my personal experience APPLY has no performance issues when the database is properly indexed and statistics are up to date (just like a normal query with subqueries behaves in such conditions)</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