PostgreSQL-计算行之间的差异

时间:2019-12-17 13:33:32

标签: sql postgresql

下面的大家好是我的数据库架构,我需要能够生成一个查询,以便针对每一个史诗,了解现在的bid_px和5分钟前的bid_px之间的差异

 epic                       t                   bid_px  ask_px
 MARKET:IX.D.FANG.DAILY.IP  2019-12-17 13:25:19  2985.5 2988.5
 MARKET:IX.D.FTSE.MONTH1.IP 2019-12-17 13:25:17  7516.3 7520.3
 MARKET:IX.D.FTSE.MONTH1.IP 2019-12-17 13:25:15  7515.8 7519.8
 MARKET:IX.D.FTSE.MONTH1.IP 2019-12-17 13:25:15  7516   7520
 MARKET:KB.D.MID250.MAR.IP  2019-12-17 13:25:15 21700  21852
 MARKET:IX.D.FTSE.MONTH1.IP 2019-12-17 13:25:14  7516   7520
 MARKET:KB.D.MID250.DEC.IP  2019-12-17 13:25:13 21645  21775
 MARKET:KB.D.MID250.DEC.IP  2019-12-17 13:25:11 21645  21776

我提出了以下查询:

SELECT 
  (SELECT bid_px as val2
    from
      ig_markets where t<NOW() order by t desc limit 1
  ) - 
    (SELECT bid_px as val1
    from
      ig_markets WHERE t<NOW()- INTERVAL '3 minutes' order by t desc limit 1
  )  AS  total_count  

上面显示的是每个史诗的总计结果,我希望列出史诗及其差异,例如:

epic | total_count 
MARKET:IX.D.FANG.DAILY.IP,10
MARKET:KB.D.MID250.DEC.IP,-10
MARKET:IX.D.FTSE.MONTH1.IP,6

1 个答案:

答案 0 :(得分:0)

我不太确定我是否理解您的问题,但是我相信单个子查询可以为您提供帮助,例如

SELECT 
  t1.epic, t1.bid_px -
  (SELECT t2.bid_px FROM ig_markets t2
   WHERE t2.epic = t1.epic AND
         t2.t < now() - INTERVAL '3 minutes' 
   ORDER BY t DESC LIMIT 1)
FROM ig_markets t1
WHERE t1.t < now();

编辑:删除重复(未调试)并选择最后一个时间戳-请参阅下面的评论。

SELECT DISTINCT ON (t1.epic) 
  t1.epic, t1.bid_px - 
  (SELECT t2.bid_px 
  FROM ig_markets t2 
  WHERE t2.epic = t1.epic AND t2.t < now() - INTERVAL '3 minutes' 
  ORDER BY t DESC LIMIT 1) 
FROM ig_markets t1 WHERE t1.t < now()

或使用CTE

WITH j AS (
SELECT t,
  t1.epic, t1.bid_px -
  (SELECT t2.bid_px FROM ig_markets t2
   WHERE t2.epic = t1.epic AND
         t2.t < now() - INTERVAL '3 minutes' 
   ORDER BY t DESC LIMIT 1) AS diff
FROM ig_markets t1
WHERE t1.t < now() )
SELECT DISTINCT ON (epic) max(t), epic, diff FROM j
GROUP BY epic, diff
ORDER BY epic;