按别名选择特定的列,然后按其顺序排序

时间:2019-04-16 06:10:53

标签: sql postgresql sql-order-by

我的桌子如下

+----+----------+--------+
| id | priority |  User  |
+----+----------+--------+
|  1 |        2 | [null] |
|  2 |        1 | [null] |
|  3 |        3 | Tony   |
|  4 |        2 | John   |
|  5 |        2 | Andy   |
|  6 |        1 | Mike   |
+----+----------+--------+

我的目标是提取它们,并根据以下组合条件进行排序:

  1. 优先级= 1
  2. 用户为空
+----+----------+--------+-----------+
| id | priority |  User  | peak_rows |
+----+----------+--------+-----------+
|  1 |        2 | [null] | 1         |
|  2 |        1 | [null] | 1         |
|  6 |        1 | Mike   | 0         |
|  3 |        3 | Tony   | 1         |
|  4 |        2 | John   | 0         |
|  5 |        2 | Andy   | 0         |
+----+----------+--------+-----------+

这是我想我能做的

select
    id,
    CASE WHEN priority = 1 THEN 1 ELSE 0 END as c1,
    CASE WHEN User is NULL THEN 1 ELSE 0 END as c2,
    c1 + c2 AS peak_rows
FROM mytable
ORDER BY peak_rows DESC

但是会导致错误:

ERROR:  column "c1" does not exist
LINE 5:  c1+ c2as pp
         ^
SQL state: 42703
Character: 129

我不知道为什么要创建2列(c1和c2),但是以后不能使用。

有什么好主意吗?

3 个答案:

答案 0 :(得分:1)

您不会创建两列,以后再使用它们,而是在创建它们并希望同时使用它们。您可以使用子查询。

SELECT a.id, a.priority, a.User, a.c1 + a.c2 AS peak_rows
FROM
(SELECT id,
        priority,
        User,
        CASE WHEN priority = 1 THEN 1 ELSE 0 END as c1,
        CASE WHEN User IS NULL THEN 1 ELSE 0 END as c2,
 FROM mytable) a
ORDER BY peak_rows DESC;

答案 1 :(得分:1)

我想您的目标是按c1c2排序,因此您可以直接在order by子句中使用。您只需要在0语句中交换1case..when。并且根据您的priority=1标准,id=2必须保持在顶部。

with mytable( id, priority, "User" ) as
(
 select 1 , 2,  null  union all
 select 2,  1,  null  union all
 select 3,  3, 'Tony' union all
 select 4,  2, 'John' union all
 select 5,  2, 'Andy' union all
 select 6,  1, 'Mike'
)    
select * 
  from mytable
 order by ( case when priority = 1   then 0 else 1 end ) +
          ( case when "User" is null then 0 else 1 end );

id  priority   User
--  -------- -------
2   1         [null]
1   2         [null]
6   1          Mike
3   3          Tony
4   2          John
5   2          Andy

Demo

答案 2 :(得分:1)

select
    id,
    CASE WHEN priority = 1 THEN 1 ELSE 0 END as c1,
    CASE WHEN User is NULL THEN 1 ELSE 0 END as c2,
    (CASE WHEN priority = 1 THEN 1 ELSE 0) + ( CASE WHEN User is NULL THEN 1 ELSE 0 END) AS peak_rows
FROM mytable
ORDER BY peak_rows DESC