Sql 如何在单个查询中对子项和父项进行分组?

Sql 如何在单个查询中对子项和父项进行分组?,sql,postgresql,sorting,grouping,Sql,Postgresql,Sorting,Grouping,我有一个表,它表示一个简单的父->子层次结构,类似于: Table "public.transactions" Column | Type | Modifiers -----------+---------------+----------------------------------------------------------- id | integer | not null default nextval

我有一个表,它表示一个简单的父->子层次结构,类似于:

             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
我想在表中显示子事务(父事务id大于0的事务),这些子事务分组在各自的父事务下面。e、 g

parent
   child
   child
parent
   child
parent
parent
(注意:此处的嵌套空间仅用于直观地表示层次结构,查询结果不需要它们)

我可以在一个查询中完成此操作吗?我正在运行Postgresql 9.3,以备不时之需。

对于单一级别的嵌套,这似乎微不足道:

SELECT *
FROM   transactions
ORDER  BY COALESCE(parent_id, id), id
对于单个嵌套级别,这看起来几乎微不足道:

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

这些问题应该提供示例数据,最好是SQLFIDLE。另外:您尝试过什么?所有SQL引擎都使用关系,可以将其视为表格结构。您提供的嵌套视图不是表格式的,因此查询不能返回类似的任何内容。您可以返回类似于
parent1 child1\n parent1 child2\n parent2 child1…
@voithos嵌套只是为了直观地表示层次结构,它不需要作为查询的一部分。嵌套的级别有多少?此类问题应该提供示例数据,最好是SQLFIDLE。另外:您尝试过什么?所有SQL引擎都使用关系,可以将其视为表格结构。您提供的嵌套视图不是表格式的,因此查询不能返回类似的任何内容。您可以返回类似于
parent1 child1\n parent1 child2\n parent2 child1…
@voithos嵌套只是为了直观地表示层次结构,它不需要作为查询的一部分。有多少层嵌套?这不是组…这是顺序…尝试按名称排序(父项按名称排列,同时按名称排列-子项)这不是组…这是顺序…尝试按名称排列(父项按名称排列,同时按名称排列-子项)