根据列ID(顺序)将所选数据合并到同一行

时间:2017-06-26 20:06:32

标签: sql postgresql sql-order-by grouping postgresql-9.6

我有一组表格,用于描述人们的位置流量。主要的'travel_flows'表格具有如下表中所示的结构。流的顺序由'order_id'列描述。

+-----------+------------+---------+-------------+----------+
| travel_id | purpose_id | name_id | location_id | order_id |
+-----------+------------+---------+-------------+----------+
|       434 |         23 |      55 |          85 |        1 |
|       212 |         43 |      55 |          45 |        2 |
|       411 |         41 |      55 |          17 |        3 |
|       148 |         23 |      32 |          32 |        1 |
|       153 |         11 |      32 |          19 |        2 |
+-----------+------------+---------+-------------+----------+

我想用PostgreSQL 9.6实现的目的是根据'location_id'和'order_id'值以二进制原点(from)/ destination(to)格式将返回的行按'name_id'分组,类似于以下内容表:

+-----------------+--------------+------------------+---------------+------------+----------------+
| from_purpose_id | from_name_id | from_location_id | to_purpose_id | to_name_id | to_location_id |
+-----------------+--------------+------------------+---------------+------------+----------------+
|              23 |           55 |               85 |            43 |         55 |             45 |
|              43 |           55 |               45 |            41 |         55 |             17 |
|              23 |           32 |               32 |            11 |         32 |             19 |
+-----------------+--------------+------------------+---------------+------------+----------------+

有没有办法用select语句实现这个目的?

2 个答案:

答案 0 :(得分:2)

您可以使用lead窗口功能执行此操作。

select * from (
select purpose_id,name_id,location_id,
lead(purpose_id) over(partition by name_id order by order_id) as to_purpose_id,
lead(name_id) over(partition by name_id order by order_id) as to_name_id,
lead(location_id) over(partition by name_id order by order_id) as to_location_id
from tbl
) t
where to_purpose_id is not null and to_name_id is not null and to_location_id is not null

答案 1 :(得分:1)

您可以使用窗口函数轻松实现此目的(请参阅https://www.postgresql.org/docs/current/static/tutorial-window.html),特别是函数lead()

with flow as (
  select
    name_id,
    purpose_id as from_purpose_id,
    lead(purpose_id) over w1 as next_purpose_id,
    location_id as from_location_id,
    lead(location_id) over w1 as next_location_id,
    order_id
  from travel_flows
  window w1 as (partition by name_id order by order_id)
)
select
  name_id, from_purpose_id, next_purpose_id, from_location_id, next_location_id
from flow
where next_purpose_id is not null
order by name_id, order_id
;