我目前有一个sql语句工作,它聚合一些数据以获得具有相同id的表的子集的多行输出(不是简单的最大/最小计算)。以下剪辑根据位置的变化计算特定ID所花费的时间。
WITH id_locations AS (
SELECT created_at, id, location
FROM locations
WHERE id = 1
), travel_locations AS (
SELECT created_at, id, location, ROW_NUMBER() OVER(ORDER BY created_at) AS row_num
FROM id_locations
WHERE
created_at IN (
SELECT min(created_at)
FROM id_locations
GROUP BY location
) OR created_at IN (
SELECT max(created_at)
FROM id_locations
GROUP BY location
)
)
SELECT a.id id, a.created_at departed_at, b.created_at arrived_at, a.location departure_location, b.location arrival_location
FROM travel_locations AS a
INNER JOIN travel_locations AS b
ON a.row_num = b.row_num - 1
WHERE a.location <> b.location;
Data
id created_at location
1 1 1
1 2 1
1 3 2
1 4 2
1 5 5
1 6 5
1 7 5
1 8 5
2 1 1
2 2 1
2 3 1
2 4 1
2 5 3
2 6 3
2 7 3
2 8 3
Desired Output
id departed_at arrived_at departure_location arrival_location
1 2 3 1 2
1 4 5 2 5
2 4 5 1 3
我想创建一个包含此sql语句输出的视图,在按ID分组的表的每个子集上运行
有没有办法用raw sql做这个,或者我需要用一些sql客户端迭代所有可能的id,运行相同的查询,并将结果插入表中以供将来参考?
我使用postgresql 9.6作为参考
答案 0 :(得分:0)
SELECT id,
max_created_at AS departed_at,
next_created_at AS arrived_at,
location AS departure_location,
next_location AS arrival_location
FROM
(SELECT id,
created_at,
location,
max(created_at) over(partition by id,location) AS max_created_at,
lead(created_at) over(partition by id order by location,created_at) AS next_created_at,
lead(location) over(partition by id order by location,created_at) AS next_location
FROM locations) t
WHERE max_created_at=created_at AND next_created_at IS NOT NULL
<强> Sample Demo
强>
您尝试获取的是max
created_at和相应的位置以及下一个created_at,ID的位置。
max
窗口函数为每个ID,位置获取max
created_at。lead
从每个ID的下一行(按位置,created_at排序)获取位置,created_at值。max_created_at
等于当前行的created_at且next_created_at不为空的行。