5

我有一个交易数据表,是对未来的预测。由相同日期、类型、位置和产品标识的相同预测因此会被多次读取,因为随着时间的推移预测变得更加准确并被重新发送。

我想创建一个查询,它将具有相同类型和相同位置、产品和日期的事务分组,然后从这些组中仅选择具有最新更新时间戳的事务。

该表现在有数十万行,随着时间的流逝,数百万行,因此将不胜感激一个合理有效的解决方案:)

示例表:

date    |  location_code   | product_code  | quantity |   type   | updated_at 
------------+------------------+---------------+----------+----------+------------
2013-02-04 | ABC | 123 |  -26.421 | TRANSFER | 2013-01-12
2013-02-07 | ABC | 123 |    -48.1 | SALE | 2013-01-10
2013-02-06 | BCD | 234 |  -58.107 | SALE | 2013-01-11
2013-02-06 | BCD | 234 |      -60 | SALE | 2013-01-10
2013-02-04 | ABC | 123 |   -6.727 | TRANSFER | 2013-01-10

期望的结果:

date    |  location_code   | product_code  | quantity |   type   | updated_at 
------------+------------------+---------------+----------+----------+------------
2013-02-04 | ABC | 123 |  -26.421 | TRANSFER | 2013-01-12
2013-02-07 | ABC | 123 |    -48.1 | SALE | 2013-01-10
2013-02-06 | BCD | 234 |  -58.107 | SALE | 2013-01-11

我试过例如:

SELECT t.date, t.location_code, t.product_code, t.quantity, t.type, t.updated_at
FROM transactions t
INNER JOIN
(
   SELECT MAX(updated_at) as max_updated_at
   FROM transactions
   GROUP BY product_code, location_code, type, date
) s on t.updated_at=max_updated_at; 

但这似乎需要很长时间并且似乎不起作用。

感谢您的帮助!

4

3 回答 3

4
select distinct on ("date", location_code, product_code, type)
    "date",
    location_code,
    product_code,
    quantity,
    type,
    updated_at
from transactions t
order by t."date", t.location_code, t.product_code, t.type, t.updated_at desc
于 2013-03-16T22:45:34.850 回答
2

这可能比与派生表的联接更有效

select *
from (
    select date, 
           location_code, 
           product_code, 
           quantity, 
           type, 
           updated_at, 
           max(updated_at) over (partition by product_code, location_code, type, date) as max_updated
    from transactions
) t
where updated_at = max_updated;
于 2013-03-16T22:49:30.787 回答
1

谢谢丹布拉库克!

这是正确的查询:

SELECT t.date, t.location_code, t.product_code, t.quantity, t.type, t.updated_at
FROM transactions t
INNER JOIN
(
   SELECT MAX(updated_at) as max_updated_at, product_code prod, location_code loc, type     typ, date dat
   FROM transactions
   GROUP BY product_code, location_code, type, date
   ) s ON t.updated_at=max_updated_at AND t.location_code=loc AND t.product_code=prod AND  t.type=typ AND t.date=dat;
于 2013-03-16T22:43:54.337 回答