返回WHERE子句不完全匹配的行

时间:2018-12-04 16:22:24

标签: sql postgresql select

我预先为问题标题致歉。我真的很难写些简洁的东西!

我有一个类似于以下表格:

Item

我想编写一个查询,以便在给定特定日期时,它为表中的每个唯一Value返回一行,并在给定日期为<{1}},或者如果在给定的日期未观察到,则为上次观察到的时间

因此,使用上表,如果我提供2018-12-01,它将返回:

| Item    | Date       | Value |
| A       | 2018-12-01 | 1     |
| B       | 2018-12-01 | 2     |
| C       | 2018-12-01 | 2     |

但是如果我提供2018-12-02,它将返回:

| Item    | Date       | Value |
| A       | 2018-12-02 | 3     |
| B       | 2018-12-02 | 3     |
| C       | 2018-12-01 | 2     |

2 个答案:

答案 0 :(得分:5)

您可以使用 public zoom = () => { const newXScale = event.transform.rescaleX(this.xScale); const newYScale = event.transform.rescaleY(this.yScale); this.xAxisGroup.call(this.xAxis.scale(newXScale)); this.yAxisGroup.call(this.yAxis.scale(newYScale)); this.xGridGroup.call(this.xGrid.scale(newXScale)); this.yGridGroup.call(this.yGrid.scale(newYScale)); this.line.x(d => newXScale(d.timestamp)).y(d => newYScale(d.value)); this.lineGroup.attr("d", this.line as any); this.lineFiltered.attr("d", this.line as any); // removed the comment of this line };

distinct on

答案 1 :(得分:1)

一种方法可能是查询该日期或该日期之前的所有行,然后使用rank窗口函数获取每个项目的第一行:

SELECT item, date, value
FROM   (SELECT item, date, value, RANK() OVER (PARTITION BY item ORDER BY date DESC) AS rk
        FROM   mytable
        WHERE  date <= :param_date) t
WHERE  rk = 1