Order By is only applied to the final result except in the case of the TOP statement. Therefore, allowing Order By in a sub query without a TOP statement serves no purpose. Why would you want to order the result of a sub-query? Terry L. Broadbent - DBA
Computing Links:
I wanted to order the result of my sub-query so that I could effectively move to the "previous n rows" - in a method for paging in a web-interface that can return hundreds of rows.
Parameters: @numRows - the number of rows to be returned
@dateFrom & @dateTo - a date range that the returned rows must be within
@dateEdge - a date on the cusp of what was returned by the last query call (specifying this figure is done by the calling class). Rough code:
SELECT *
FROM (
SET ROWCOUNT @numRows
SELECT (Some select stuff that works and aggregates data based on date - returns one row for each date)
FROM tblBalancesAsAt
WHERE AsAtDate >= @dateFrom
and AsAtDate <= @dateTo
and AsAtDate < @dateEdge
GROUP BY AsAtDate
ORDER BY AsAtDate DESC
)
ORDER BY AsAtDate ASC
The logic behind this query is (with example):
1. Run the inner query to find rows with dates within the specified range, and take out the n rows immediately preceding the "date cusp" (ie. When the resulting rows are ordered by date DESC, the "top" n will be the ones immediately preceding the date cusp.
2. Return these rows in the right (ASC) order!
I couldn't find a way to implement this however. Any ideas?
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.