sql – CASE WHEN语句为ORDER BY子句

前端之家收集整理的这篇文章主要介绍了sql – CASE WHEN语句为ORDER BY子句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用sql Server 2008 R2.

我希望在表中记录的优先级排序.

所以我在ORDER BY子句中使用CASE WHEN语句. ORDER BY子句如下:

ORDER BY 
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount desc,TblList.LastName ASC,TblList.FirstName ASC,TblList.MiddleName ASC END,CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount desc,Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount DESC,CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount DESC,Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount DESC,Patlist.MiddleName ASC END

但是它在关键字’desc’附近提供了错误的语法

任何解决方

另外我可以有TblList.PinRequestCount<> 0和TblList.HighCallAlertCount<> 0和TblList.HighAlertCount<> 0和TblList.MediumCallAlertCount<> 0和TblList.MediumAlertCount<> 0同时.

解决方法

CASE是一个表达式 – 它返回单个标量值(每行).它不能返回其他东西的解析树的复杂部分,如SELECT语句的ORDER BY子句.

看起来你只需要:

ORDER BY 
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,TblList.MiddleName ASC

或者可能:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,TblList.MiddleName ASC

告诉您上述哪些(或其他)是您正在寻找的,这有点棘手,因为您已经a)没有解释您要实现的实际排序顺序,以及b)没有提供任何样本数据和预期的结果,我们可以尝试推断您要实现的实际排序顺序.

这可能是我们要找的答案:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN 5
   WHEN TblList.HighCallAlertCount <> 0 THEN 4
   WHEN TblList.HighAlertCount <> 0 THEN 3
   WHEN TblList.MediumCallAlertCount <> 0 THEN 2
   WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,TblList.MiddleName ASC

猜你在找的MsSQL相关文章