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

相关文章

(一)日志传送架构 (1.1)相关服务器 主服务器 :用于生产的服务器,上面运行这生产SQL Server数据库...
(一)事故背景 最近在SQL Server 2012生产数据库上配置完事物复制(发布订阅)后,生产数据库业务出现了...
(一)测试目的 目前公司使用的SQL SERVER 2012高可用环境为主备模式,其中主库可执行读写操作,备库既...
(一)背景个人在使用sql server时,用到了sql server的发布订阅来做主从同步,类似MySQL的异步复制。在...
UNION和OR谓词 找出 product 和 product2 中售价高于 500 的商品的基本信息. select * from product wh...
datawhale组队学习task03