ben*_*ier 1 sql sorting postgresql 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
Run Code Online (Sandbox Code Playgroud)
我想显示包含子事务的表(parent_id> 0的表)分组在他们各自的父母下面.例如,
parent
child
child
parent
child
parent
parent
Run Code Online (Sandbox Code Playgroud)
(注意:嵌套空格仅在此处以可视方式表示层次结构,查询结果不需要它们)
我可以在一个查询中执行此操作吗?我正在运行Postgresql 9.3以防万一.
对于单级嵌套,这看起来几乎是微不足道的:
SELECT *
FROM transactions
ORDER BY COALESCE(parent_id, id), id
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1229 次 |
最近记录: |