Postgres - 使用步/分辨率获取两个日期之间的记录

时间:2018-03-28 01:30:15

标签: sql postgresql

我有一个问题:

SELECT * FROM price_events 
WHERE code='BCI.AX' AND date BETWEEN (now() - interval '1 month') AND now() 
ORDER BY date DESC;

这可能会给我带来数百行。我想提炼下来说10行,均匀分布。这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

一种方法是使用行号技巧来识别每import { Component, OnInit, AfterViewInit } from '@angular/core'; import {MyClass} from "..myClass" declare var jsObject: any; @Component({ selector: 'app-rankuser', templateUrl: './rankuser.component.html', styleUrls: ['./rankuser.component.css'] }) export class RankuserComponent implements OnInit, AfterViewInit { constructor(private mc:MyClass) { } ngAfterViewInit() { mc.chartRank(); } ngOnInit() { } } 个步骤发生的记录,比如说10个步骤。我们可以检查行号是否是步长的倍数,如果是,则保留该记录。

n

答案 1 :(得分:1)

您可以通过以下方式随机抽取样本:

SELECT pe.*
FROM price_events  pe
WHERE code = 'BCI.AX' AND date BETWEEN (now() - interval '1 month') AND now() 
ORDER BY random()
LIMIT 10;

对于大多数目的而言,这通常是足够好的。如果要将数据分组并从每个组中选择一个,则可以使用ntile()

SELECT DISTINCT ON (nt) pe.*
FROM (SELECT pe.*,
             NTILE(10) OVER (ORDER BY date) as nt -- speculating that you want date
      FROM price_events  pe
      WHERE code = 'BCI.AX' AND date BETWEEN (now() - interval '1 month') AND now() 
     ) pe
ORDER BY nt DESC;

你真正想要的是第一个记录,然后是均匀间隔的记录。这更像是这样:

select pe.*
from (select pe.*,
             count(*) over () as cnt,
             row_number() over (order by date) as seqnum
      from price_events  pe
      where code = 'BCI.AX' and date between (now() - interval '1 month') and now() 
      ) pe
where seqnum in 1 or
      (seqnum % floor(cnt / 9)) = 0;

如果你想要中间的第一个,最后一个和均匀间隔的记录,这会变得更加复杂。但是之前的方法之一可能适合你。