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

后端 未结 3 682
太阳男子
太阳男子 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: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
    

提交回复
热议问题