PostgreSQL - 复杂查询中两行之间的日期差异
PostgreSQL - Date difference between two rows in complex query
我有这个查询:
SELECT apple, banana, update_at FROM
(
SELECT DISTINCT ON (apple) *
FROM table
WHERE apple IN ('ad', 'sa')
ORDER BY apple, update_at DESC
) q
此查询的目的是获取具有 apple
"ad" 或 "sa" 的行,以及 return 最新的行(update_at (timestamp)
). 此查询有效。
我的问题是我希望查询将显示查询匹配行和它之前的行的时间戳(持续时间)之间的差异,而不是 update_at
列。
示例:
apple---|banana---|update_at
============================
ad------|VAL------|2017-06-01 12:12:30
ad------|VAL------|2017-06-01 09:00:00
ad------|VAL------|2017-05-31 13:41:00
结果:
apple---|banana---|update_at
============================
ad------|VAL------|**03:12:30**
03:12:30 是时长。
希望说得够清楚。
您需要为此使用 window 函数:
SELECT apple,
banana,
update_at,
prev_update_at,
update_at - prev_update_at as duration
FROM (
SELECT *,
row_number() over (partition by apple order by update_at desc) as rn,
lag(update_at) over (partition by apple order by update_at) as prev_update_at
FROM table
WHERE apple IN ('ad', 'sa')
) q
where rn = 1;
我有这个查询:
SELECT apple, banana, update_at FROM
(
SELECT DISTINCT ON (apple) *
FROM table
WHERE apple IN ('ad', 'sa')
ORDER BY apple, update_at DESC
) q
此查询的目的是获取具有 apple
"ad" 或 "sa" 的行,以及 return 最新的行(update_at (timestamp)
). 此查询有效。
我的问题是我希望查询将显示查询匹配行和它之前的行的时间戳(持续时间)之间的差异,而不是 update_at
列。
示例:
apple---|banana---|update_at
============================
ad------|VAL------|2017-06-01 12:12:30
ad------|VAL------|2017-06-01 09:00:00
ad------|VAL------|2017-05-31 13:41:00
结果:
apple---|banana---|update_at
============================
ad------|VAL------|**03:12:30**
03:12:30 是时长。
希望说得够清楚。
您需要为此使用 window 函数:
SELECT apple,
banana,
update_at,
prev_update_at,
update_at - prev_update_at as duration
FROM (
SELECT *,
row_number() over (partition by apple order by update_at desc) as rn,
lag(update_at) over (partition by apple order by update_at) as prev_update_at
FROM table
WHERE apple IN ('ad', 'sa')
) q
where rn = 1;