sam ali
sam ali

Reputation: 67

How to sort top 4 values with SQL Server which contains negative numbers

Input file

    SN  ID
   ------------
    1   55
    2  -25
    3   62
    4  -0.05
    5   0.0 

Output file should be after sorting

 SN  ID
 -------
  3  62
  1  55
  5  0.0
  4 -0.05
  2  -25

Using this SQL Server command need to modify by logic

select top 4 * 
from filename 
order by ID desc

Upvotes: 0

Views: 206

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522211

It sounds as though perhaps your ID column is actually some sort of text, rather than numeric, type. If so, then casting the column to a decimal and then sorting should fix the problem:

SELECT TOP 4 * 
FROM filename 
ORDER BY CAST(ID AS DECIMAL(10,4)) DESC;

Note that if the above query does work, then you should seriously consider not storing numeric information as text.

Upvotes: 3

gotqn
gotqn

Reputation: 43656

You are missing a WHERE clause. If you need to filter only by negative values just add the following:

select top 4 * 
from filename
where ID < 0 
order by ID desc

Upvotes: 0

Related Questions