簡體   English   中英

根據列ID(順序)將所選數據合並到同一行

[英]Combine selected data into same row based on column id (order)

我有一些表的組合,用於描述人員的位置流。 主“ 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'值以二進制origin(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語句實現這一目標嗎?

您可以使用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

您可以使用“窗口函數”(請參見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
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM