如何在postgres中查询最近更新日期的相同类别AVG值?

How to query the same categories AVG value of recently updated date in postgres?

是否可以在 Postgres 中的单个查询中执行如下操作?

Table: 姓名

-------------------------------------
| id    | unique_name   | category  |
-------------------------------------
| 1     | A             | One       |
| 2     | B             | One       |
| 3     | C             | One       |
| 4     | D             | Two       |
| 5     | E             | Two       |
| 6     | F             | Two       |
| 7     | G             | Three     |
| 8     | H             | Three     |
-------------------------------------

Table: 价格

-----------------------------------------------------
| id    | name_id       | amount    | updated_date  |
-----------------------------------------------------
| 1     | 1             | 4.3       | 20-06-2020    |
| 2     | 2             | 2.3       | 20-06-2020    |
| 3     | 2             | 2.4       | 18-06-2020    |
| 4     | 3             | 4.4       | 20-06-2020    |
| 5     | 3             | 6.3       | 15-06-2020    |
| 6     | 4             | 0.2       | 10-06-2020    |
| 7     | 4             | 0.3       | 15-06-2020    |
| 8     | 4             | 7.4       | 20-06-2020    |
| 9     | 5             | 3.4       | 20-06-2020    |
-----------------------------------------------------

我有一个像上面那样的 table 结构。

我想要最近更新的同类商品的平均数量。

如下所示:

-----------------------------
| avg           | category  |
-----------------------------
| 3.66          | One       |     (4.3 + 2.3 + 4.4) / 3
| 5.4           | Two       |     (7.4 + 3.4) / 2
-----------------------------

您可以使用 distinct on 获取每个 name_id 的最新 price 行,然后加入 name table 并聚合:

select n.category, avg(p.price) avg_price
from name n
inner join (
    select distinct on(name_id) p.*
    from price p
    order by name_id, updated_at desc
) p on p.name_id = n.id
group by n.category

如果您想要最近日期的平均价格,那么您可以使用:

select n.category, avg(p.price)
from name n join
     price p
     on p.name_id = n.id
where p.updated_at = (select max(p2.updated_at) from price)
group by n.category;

这似乎接近您的要求。