如何使用包含负数的SQL Server对前4个值进行排序

时间:2017-11-21 06:20:54

标签: sql sql-server

输入文件

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

输出文件应在排序后

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

使用此SQL Server命令需要按逻辑

进行修改
select top 4 * 
from filename 
order by ID desc

2 个答案:

答案 0 :(得分:3)

听起来好像你的ID列实际上是某种文本,而不是数字类型。如果是这样,然后将列转换为小数,然后排序应解决问题:

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

请注意,如果上述查询确实有效,那么您应该认真考虑不将数字信息存储为文本。

答案 1 :(得分:0)

您缺少select top 4 * from filename where ID < 0 order by ID desc 条款。如果您只需按<button onClick="myfun()">+</button> <!--<button onClick="myfun()" id="pluse">+</button>--> <input type="text" id="pluse" > <button onClick="myfun1()">_</button> var a = 0; function myfun(){ a++; document.getElementById('pluse').value = a; //document.getElementById('pluse').innerHTML = a; } function myfun1(){ a--; document.getElementById('pluse').value = a; } 过滤,只需添加以下内容:

CREATE PROCEDURE uspInserUpdateDeleteSelect 
    -- Add the parameters for the stored procedure here
    @QueryType varchar(10),
    @ID int = 0,
    @Field1 int = 0,
    @Field2 varchar(20) = NULL

BEGIN
        IF @QueryType = 'INSERT' BEGIN
            INSERT INTO MyTable (Field1, Field2) VALUES (@Field1, @Field2)
        END

        ELSE IF @QueryType = 'UPDATE' BEGIN
            UPDATE MyTable 
            SET Field1 = @Field1, Field2 = @Field2
            WHERE ID=@ID
        END

        ELSE IF @QueryType = 'DELETE' BEGIN
            DELETE FROM MyTable
            WHERE ID=@ID
        END

        ELSE IF @QueryType = 'SELECTALL' BEGIN
            SELECT * FROM MyTable
        END

        ELSE IF @QueryType = 'SELECTBYID' BEGIN
            SELECT * FROM MyTable WHERE ID=@ID  
        END

END


//For params Error, create a new class and pass as list of the class

    public class ParaNameValue
    {
        public string ParaName{ get; set; }
        public string ParaValue{ get; set; }

        public ParaNameValue(string PName, string PValue){
            this.ParaName=PName;
            this.ParaValue = PValue;
        }
    }

//For caller function, how to pass parameter list

    List<ParaNameValue> ListPara= new List<ParaNameValue>();
    ListPara.Add(new ParaNameValue("@Name", "BlaBla 1");
    ListPara.Add(new ParaNameValue("@Email", "BlaBla 2");

    GetDataSet(string storedProcedure, ListPara);


//for dataset function
    public static DataSet GetDataSet(string storedProcedure, List<ParaNameValue> ParaList)"
    {
        //do other stuffs here

        //getting sqlpara values
        foreach (ParaNameValue p in ParaList)
        {
             c.getcmd.Parameters.Add(new SqlParameter(p.ParaName, p.ParaValue));
        }
    }
相关问题