联合全部后排序或按案例排序时

时间:2013-05-23 13:03:32

标签: php sql sorting sql-order-by

要测试这些查询,我在Microsoft Access的SQL查询向导中运行它们。我正在尝试修改现有的php文件,以便在顶部显示高优先级状态警报(O和P),然后由opslogid按降序排序。在没有O和P状态警报之后,我想显示其余的状态警报(A,I,R),由opslogid以降序排序。这是样本数据和所需输出:

tblOpslog

opslogid = 9999, 9998, etc.

status = R, O, I, A, P

opslogid                               status

9999                                       P

9996                                       P

9994                                       O

9991                                       O

9998                                       I

9997                                       I

9980                                       A

9979                                       A

9978                                       A

9930                                       R

9928                                       R

我的同事建议我使用union all命令,这导致我提出这个:

注意:WHERE DELETED AND NO VIEW MUST REMAIN IN QUERY, IT IS VITAL IN THE OUTPUT OF THE DATABASE”。我也无法对数据库本身进行任何更改。

select * from (SELECT * FROM tblOpslog
Where Deleted = No AND Noview = No AND status in ('O','P'))
union all
select * from (Select * FROM tblOpslog Where Deleted = No AND Noview = No AND status in ('I','R', 'A'))
Order by status, opslogid DESC;

这个输出是:

opslogid                               status

9980                                       A

9979                                       A

9978                                       A

9998                                       I

9997                                       I

9994                                       O

9991                                       O

9999                                       P

9996                                       P

9930                                       R

9928                                       R

我也试过这段代码:

SELECT *
FROM tblOpsLog
WHERE Deleted = No AND Noview = No AND status IN ('A', 'I', 'R', 'O', 'P')
ORDER BY CASE WHEN status IN ('O', 'P') then 1
              ELSE 2
         END, opslogid DESC

这给了我这个错误:

Syntax error (missing oeprator) in query expression 'CASE WHEN status IN ('O','P') then 1 ELSE 2 End'.

如果有人可以建议修复/添加代码以显示所需的输出,我真的很感激吗?谢谢

2 个答案:

答案 0 :(得分:1)

您正在使用不支持case语句的Access。使用Access语法试用此版本:

SELECT *
FROM tblOpsLog
WHERE Deleted = No AND Noview = No AND status IN ('A', 'I', 'R', 'O', 'P')
ORDER BY iif(status IN ('O', 'P'), 1, 2),
         opslogid DESC

答案 1 :(得分:0)

试试这个:

SELECT * FROM tblOpsLog WHERE Deleted = No AND Noview = No 
AND status IN ('A', 'I', 'R', 'O', 'P')
ORDER BY CASE status WHEN 'P' then 1
WHEN 'O' then 1
ELSE 2
END, opslogid DESC