带多列排序的order by子句的案例声明

时间:2019-08-12 11:01:15

标签: sql-server sql-order-by

我编写以下SQL查询以按某种条件获取数据顺序,

SELECT @NullCount = COUNT(1)
FROM @ServicesForBranch where SortValue IS NULL;

SELECT @ServiceCount = COUNT(1) 
FROM Service;

SELECT * FROM @tmp t

WHERE t.IsActive = 1 
    ORDER BY
    CASE WHEN @NullCount = @ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue,t.Name END  

但是错误t.BranchServiceSortValue,t.Name在此行显示为

incorrect syntax near ','

我在这里写错了什么?

2 个答案:

答案 0 :(得分:0)

每个CASE语句仅返回1个值,因此您需要另一个值:

ORDER BY
CASE WHEN @NullCount = @ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END,
CASE WHEN @NullCount <> @ServiceCount THEN t.Name END

但是如果SortValue是唯一的,或者您不介意对Name进行二次排序,则可以简化为:

ORDER BY
CASE WHEN @NullCount = @ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END,
t.Name

答案 1 :(得分:0)

尝试一下:

SELECT @NullCount = COUNT(1)
FROM @ServicesForBranch 
where SortValue IS NULL;

SELECT @ServiceCount = COUNT(1) 
FROM Service;

SELECT * FROM @tmp t

WHERE t.IsActive = 1 
    ORDER BY
    (CASE WHEN @NullCount = @ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END),t.Name