Sql Order By … using `Case When` for different Ascending, Descending, and Custom Orders

后端 未结 3 678
太阳男子
太阳男子 2021-02-08 00:04

I want to sort product by discount on certain condition

ORDER BY 
    CASE WHEN @OrderBy = 0
    THEN table.id END ASC,
    CASE WHEN @Orderby = 2
    THEN tabl         


        
相关标签:
3条回答
  • 2021-02-08 00:15

    It seems to me you need something similar to this

    select * from TableName where someCondition >100
      order by
        case when @OrderBy = 'AirlineService'
          then AirlineService END desc,
        case when  @OrderBy = 'SomeMore'
          then  MyOtherColumn  end
    GO
    

    If you not have a coulmn then you can not sort with that. Please read this Microsoft Link Please keep in mind - specifies the sort order used on columns returned in a SELECT statement. Hope it helps.

    0 讨论(0)
  • 2021-02-08 00:20

    There are quite a few problems, e.g. You can't alias a calculation field in an order by, and you'll need to escape your table name, fix the cae, and count the parenthesis.

    Also, since it seems you just want to CASE on a single variable, you can move the @OrderBy out to the top of the CASE, like so:

    SELECT * from [table]
    ORDER BY 
        CASE @OrderBy
            WHEN  0
                THEN [table].id -- ASC
            WHEN 2
                THEN [table].id * -1 -- DESC
        ---I want to do something like below as I don't have discount column in table
            WHEN 4
                THEN (100-([table].price/[table].oldprice)*100)
        END
    

    SqlFiddle Here

    As an aside, if you need to dynamically change the ASC or DESC of a column, you can use a hack like this by multiplying by -1.

    (Also note that ORDER BY CASE ... END ASC, CASE ... END ASC will set the first and then second orderings ... this doesn't seem to make sense given that @OrderBy can only have a single value)

    0 讨论(0)
  • 2021-02-08 00:22

    Don't calculate the discount in the ORDER BY clause but in the SELECT

    SELECT *, (100-(table.price/table.oldprice))*100 as discount
    FROM table
    

    ...

    ORDER BY 
    CASE WHEN @OrderBy = 0
    THEN table.id END ASC,
    CASE when @orderby=2
    THEN table.id END ASC,
    CASE WHEN @OrderBy = 4
    THEN discount END ASC
    
    0 讨论(0)
提交回复
热议问题