sql查询按多个条件排序

问题描述 投票:0回答:3

我想知道如何在 mysql 查询中对值进行排序。

我有一个表

tasks
并有
cost
列,其中可以包含空值或数值

其他栏

status
2703, 2702, 2701

根据条件,order by 应该是

-成本具有价值

null
并且状态应为订单
2701, 2702, 2703
始终是最后

-具有价值

numbers
的成本和仅具有
2701, 2702
的状态应该是第一个

(即)具有空值/状态为

2703
的数字的成本应该是最后一个。

尝试查询

cost status
1    2703
null 2702
2    2701

Expected order should be

cost status
2    2701
null 2702
1    2703 // alwys status `2703` should be last after null if cost has either value/null



select * from tasks t1 where active = true 
ORDER BY t1.cost IS NULL, t1.cost asc, t1.statusId asc


sql mysql model sequelize.js
3个回答
0
投票

尝试类似:

select * from tasks t1 where active = true 
ORDER BY 
CASE WHEN status = 2703 THEN 2 ELSE 1 END asc,
t1.cost IS NULL, t1.cost asc, t1.statusId asc

0
投票
select * 
from tasks t1 
where t1.active = true and t1.cost is not NULL and t1.statusID in (2701, 2702) 
union all 
select * 
from tasks t2 
where t2.active = true and t2.cost is NULL

虽然重新阅读您的问题,但您似乎只想将 NULL 成本放在底部。 为此,您所需要的只是 select * fromtasks t1 where t1.active = true order by t1.cost, t1.statusID and null 将转到底部


0
投票

用例表达:

WITH    -- S a m p l e    D a t a :
  tasks (id, cost, status ) AS
    ( Select 1, 1,    2703 Union All
      Select 2, null, 2702 Union All
      Select 3, 2,    2701 
    )
--    S Q L : 
Select   *
From     tasks
Order By Case -- cost with either null/number with status 2703 should be last
                When status = 2703 Then 9    
              --
              -- cost with value numbers and status with only 2701, 2702 should be first
                When cost Is Not Null And 
                     status IN(2701, 2702) Then 1
          --
          -- else in between 1 and 9  (cost with value number and status IN(2701, 2702) )
         Else 5
         End; 
/*
id  cost    status
--  ----  -------
 3     2     2701
 2  null     2702
 1     1     2703    */

注意:始终记住 Case 表达式是连续的,第一个为 true 的条件将返回其值并退出 Case。

© www.soinside.com 2019 - 2024. All rights reserved.