Ordering sql query results
My sql query gives columns:
-
product_id
(which is an integer) -
pnl
(which is float - can be negative)
I am getting over 100 lines.
I want to filter the top 40 rows based on abs (pnl). But the results should only be ordered by column pnl, not abs (pnl).
I want to do this for MSSQL 2005.
Is there a way to do this?
a source to share
You cannot do it in one step / stat. The selection TOP x
will always be based on the ordering instructions ORDER BY
. You cannot select TOP 40 based on ABS(pnl)
and at the same time order something else.
What you need to do is a two step process - either using a CTE (Common Table Expression) or a temporary table - first select the TOP-40 rows ordered by ABS(pnl)
, then order this result given pnl
.
Sort of:
WITH Top40Rows AS
(
SELECT TOP 40 product_id, pnl
ORDER BY ABS(pnl)
)
SELECT product_id, pnl
FROM Top40Rows
ORDER BY pnl
a source to share
Assuming product_id is not the primary key of the table, you can do something like this:
Select ...
From Table
Join (
Select TOP 40 TablePK
From Table
Order by Abs( pnl ) Desc
) As Z
On Table.TablePK = Z.TablePK
Order By Table.pnl ASC
As OMG Ponies mentioned, you can do this as a single view:
Select ...
From (
Select TOP 40 .....
From Table
Order by Abs( pnl ) Desc
) As Z
Order By Z.pnl ASC
If you want to use CTE, I would do it with the ROW_NUMBER function:
With RankedItems As
(
Select ...
, ROW_NUMBER() OVER ( ORDER BY Abs(Table.pnl) ) As ItemRank
From Table
)
Select
From RankedItems
Where ItemRank <= 40
Order By pnl ASC
a source to share