在SQL Server 2016中的按子句中按顺序的单个案例中的多列

时间:2018-10-06 07:13:39

标签: sql asp.net sql-server database sql-server-2012

我编写了一个查询,其中有一个条件,可以按如下所示按单个顺序按多列对数据进行排序。

ORDER BY Column1 ASC, Column2 ASC, Column3 ASC

ORDER BY Column1 DESC, Column2 DESC, Column3 DESC

我想通过如下表达式按条件顺序编写上述排序

ORDER BY 
    CASE WHEN @SortExpression = 'Id ASC' THEN Id END ASC,    
    CASE WHEN @SortExpression = 'Id DESC' THEN Id END DESC,    
    CASE WHEN @SortExpression = 'Status ASC' THEN Status END ASC,    
    CASE WHEN @SortExpression = 'Status DESC' THEN Status END DESC,   
    CASE WHEN @SortExpression = 'Country ASC' THEN Country Asc, City Asc, Zip Asc END,    
    CASE WHEN @SortExpression = 'Country DESC' THEN Country DESC, City DESC, Zip DESC END

但是上面的查询给出了语法错误。谁能帮我找出解决我问题的方法?

2 个答案:

答案 0 :(得分:1)

CASE WHEN @SortExpression = 'Country ASC' THEN Country Asc, City Asc, Zip Asc END,没有语法,您需要将CASE WHEN中的每个订单写成let。

如果仅@SortExpression将设置一个值。如果CASE WHEN不匹配,条件将返回NULL,则仅执行您的期望订单列。

ORDER BY 
    CASE WHEN @SortExpression = 'Id ASC' THEN Id END ASC,    
    CASE WHEN @SortExpression = 'Id DESC' THEN Id END DESC,    
    CASE WHEN @SortExpression = 'Status ASC' THEN Status END ASC,    
    CASE WHEN @SortExpression = 'Status DESC' THEN Status END DESC,   
    CASE WHEN @SortExpression = 'Country ASC' THEN Country END Asc ,
    CASE WHEN @SortExpression = 'Country ASC' THEN City END Asc ,
    CASE WHEN @SortExpression = 'Country ASC' THEN Zip END Asc ,   
    CASE WHEN @SortExpression = 'Country DESC' THEN Country END DESC , 
    CASE WHEN @SortExpression = 'Country DESC' THEN City END DESC , 
    CASE WHEN @SortExpression = 'Country DESC' THEN Zip END DESC 

答案 1 :(得分:1)

您的case语句需要按以下方式重新编写,您在(THEN Country Asc, City Asc, Zip Asc END)之后写了多列,这是不正确的

ORDER BY 
(CASE @SortExpression  when 'Id ASC'
 THEN Id End) ASC,    
(CASE @SortExpression WHEN 'Id DESC'
THEN Id END) DESC,    
(CASE @SortExpression 
WHEN 'Status ASC' 
THEN Status END ) ASC,    
(CASE @SortExpression WHEN 'Status DESC'
 THEN Status END) DESC,   
(CASE @SortExpression WHEN 'Country ASC' 
THEN Country end) Asc,
(CASE @SortExpression WHEN 'Country ASC' 
THEN City end) Asc,
(CASE @SortExpression WHEN 'Country ASC' 
THEN Zip end) Asc,         
( CASE @SortExpression  WHEN 'Country DESC'
THEN Country end ) DESC ,
( CASE @SortExpression  WHEN 'Country DESC'
THEN City end ) DESC,
( CASE @SortExpression  WHEN 'Country DESC'
THEN Zip end ) DESC