我收到了这两个问题,但无法理解如何将它们结合起来:
SELECT a.trainid, a.time AS departuretime, b.time AS arrivaltime, (b.timestamp-a.timestamp) AS journeytime, a.estimate as estimateA, b.estimate as estimateB
FROM public.snapshot AS a
INNER JOIN public.snapshot AS b ON a.trainid=b.trainid
WHERE a.location = '49K' AND NOT a.location=b.location AND (b.timestamp-a.timestamp) BETWEEN 10 AND 5000
和
SELECT a.location, ROUND(AVG(b.timestamp-a.timestamp)) AS avgjourneytime, ROUND(AVG(a.estimate)) as avgestimateA, ROUND(AVG(b.estimate)) as avgestimateB, COUNT(*) as records
FROM public.snapshot AS a INNER JOIN public.snapshot AS b ON a.trainid=b.trainid
WHERE (b.timestamp-a.timestamp) BETWEEN 180 AND 5000 AND ((#a.timestamp from query above#)%86400-a.timestamp%86400) BETWEEN -900 AND 900 AND a.location = '49K'
GROUP BY a.location
所以基本上我想要输出
a.trainid, departuretime, arrivaltime, journeytime, estimateA, estimateB, avgjourneytime, avgestimateA, avgestimateB, records
示例数据:
a.trainid, departuretime, arrivaltime, journeytime, estimateA, estimateB, avgjourneytime, avgestimateA, avgestimateB, records
54, 14:00, 14:05, 300, 600, 400, 320, 620, 420, 3
57, 15:00, 15:10, 600, 800, 400, 860, 420, 420, 4
所以对于所有的平均值,我只想要考虑前一天+/- 15分钟的那一行的出发时间的记录,所以对于第一行我只想要平均的列车之间离开13:45和14:15,以及第二排14:45到15:15之间所有列车的平均值。记录显示平均值考虑了多少记录。 另外,有没有办法区分工作日,周六和周日?
前一天的平均值在+/- 15分钟之内,时间戳值是自1970年1月1日 - UTC以来的秒数,因此模数86400是一天。
使用Postgres。
答案 0 :(得分:0)
试试这个..
select q1.*,q2.* from
(
SELECT a.trainid as trainid, a.time AS departuretime, b.time AS arrivaltime, (b.timestamp-a.timestamp) AS journeytime, a.estimate as estimateA, b.estimate as estimateB
FROM public.snapshot AS a
INNER JOIN public.snapshot AS b ON a.trainid=b.trainid
WHERE a.location = '49K' AND NOT a.location=b.location AND (b.timestamp-a.timestamp) BETWEEN 10 AND 5000
)q1,
(
SELECT a.trainid as trainid,a.location, ROUND(AVG(b.timestamp-a.timestamp)) AS avgjourneytime, ROUND(AVG(a.estimate)) as avgestimateA, ROUND(AVG(b.estimate)) as avgestimateB, COUNT(*) as records
FROM public.snapshot AS a INNER JOIN public.snapshot AS b ON a.trainid=b.trainid
WHERE (b.timestamp-a.timestamp) BETWEEN 180 AND 5000 AND ((#a.timestamp from query above#)%86400-a.timestamp%86400) BETWEEN -900 AND 900 AND a.location = '49K'
GROUP BY a.location
)q2
where q1.trainid=q2.trainid;