我编写以下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 ','
我在这里写错了什么?
答案 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