如何订购postgresql表以使连续值不匹配

时间:2017-07-24 11:43:35

标签: sql postgresql

如何编写postgresql查询或视图,返回一个表,其中第一个结果在给定列中没有任何匹配的连续值。 例如,在此表中:

+--------------------------+-------+----------------+--------+
|            id            | model |      name      | colour |
+--------------------------+-------+----------------+--------+
| 59663f188b06e815cae676f4 | ford  | amazing car    | red    |
| 59663f1487b60515ca614999 | ford  | great car      | pink   |
| 59663f230f519115cae6e089 | mini  | broken car     | blue   |
| 59663f1ce28a5315ca07262e | vw    | mystery mobile | blue   |
+--------------------------+-------+----------------+--------+

如果我选择型号或颜色,订单可能是:

+--------------------------+-------+----------------+--------+
|            id            | model |      name      | colour |
+--------------------------+-------+----------------+--------+
| 59663f188b06e815cae676f4 | ford  | amazing car    | red    |
| 59663f230f519115cae6e089 | mini  | broken car     | blue   |
| 59663f1487b60515ca614999 | ford  | great car      | pink   |
| 59663f1ce28a5315ca07262e | vw    | mystery mobile | blue   |
+--------------------------+-------+----------------+--------+

1 个答案:

答案 0 :(得分:1)

试试这个。如果数据有多个重复值

,它可能有效
Select 
   id
  ,model
  ,name
  ,colour
  ,row_number() over(partition by model) Rno
from Table
order by Rno