如何在单个查询中对儿童和父母进行分组?

时间:2013-12-04 21:01:24

标签: sql postgresql sorting grouping

我有一个表格,表示一个简单的父级>子层次结构,如:

             Table "public.transactions"
   Column  | Type          |  Modifiers
-----------+---------------+-----------------------------------------------------------
 id        | integer       | not null default nextval('transactions_id_seq'::regclass)
 parent_id | integer       | not null default 0
 amount    | numeric(15,4) | not null default 0.0000

我想显示包含子事务的表(parent_id> 0的那些)分组在他们各自的父母下面。例如,

parent
   child
   child
parent
   child
parent
parent

(注意:嵌套空格仅在此处以可视方式表示层次结构,查询结果不需要它们)

我可以在一个查询中执行此操作吗?我正在运行Postgresql 9.3以防万一。

1 个答案:

答案 0 :(得分:5)

对于单层嵌套,这看起来似乎微不足道:

SELECT *
FROM   transactions
ORDER  BY COALESCE(parent_id, id), id