使用CASE WHEN按两列排序

时间:2017-11-20 09:00:03

标签: sql-server tsql

我有这样的查询:

SELECT 
    ROW_NUMBER() OVER(ORDER BY USER_FNM, USER_LNM) AS ROW_NUM,
    USER_TEL, USER_FAX, USER_MOB            
FROM 
    BAUSER      
ORDER BY            
    CASE 
       WHEN @cOrderBy = 'USER_FNM_USER_LNM ASC' THEN USER_LNM 
    END ASC,
    CASE 
       WHEN @cOrderBy = 'USER_FNM_USER_LNM DESC' THEN USER_LNM 
    END DESC,
    CASE 
       WHEN @cOrderBy IS NULL THEN USER_KEY 
    END ASC
    OFFSET @iStartIndex ROWS
    FETCH NEXT @iRowsPerPage ROWS ONLY

我想要做的是按两列排序 - 但这显示语法错误:

CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM ASC' THEN USER_LNM, USER_FNM END ASC

在这种情况下,知道如何按两列排序吗?

1 个答案:

答案 0 :(得分:2)

CASE是一个返回单个表达式/值的表达式。您需要为每列编写一个CASE语句:

ORDER BY            
CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM ASC'        THEN USER_LNM END ASC,
CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM DESC'       THEN USER_LNM END DESC,
CASE WHEN @cOrderBy IS NULL                          THEN USER_KEY END ASC,

CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM ASC'        THEN USER_FNM END ASC,
CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM DESC'       THEN USER_FNM END DESC

更新(以反映更新的问题)

由于您有ROW_NUM列,因此可以按以下方式排序:

CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM ASC'        THEN ROW_NUM END ASC,
CASE WHEN @cOrderBy = 'USER_FNM_USER_LNM DESC'       THEN ROW_NUM END DESC,
CASE WHEN @cOrderBy IS NULL