简体   繁体   English

如何仅获取最近的值

[英]How to get last recent value only

I have two tables master table1 and detail table2 我有两个表master table1和detail table2

Table1 structure Table1结构

table1_id integer,
description varchar(50)

Table2 structure Table2结构

table2_id integer,
table1_id integer,
price numeric(7,2),
Price_date date

I need to write SQL or a view that link between these two tables but the problem I want from table2 only to get a single value that is the most recent one of the price field using the price_date field to be linked with table1 , in other words I dont want to get any duplicates from Table2.table1_id field. 我需要编写SQL或在这两个表之间建立链接的视图,但是我想要从table2获得的问题仅是使用要与table1链接的price_date字段来获取price字段中最近的一个值,换句话说我不想从Table2.table1_id字段中获取任何重复Table2.table1_id how I should write that SQL ? 我应该如何编写该SQL?

I assume you want all the latest entries for each table1_id from the table, and not just the latest entry (which is a lot simpler). 我假设您想要表中每个table1_id所有最新条目,而不仅仅是最新条目(这要简单得多)。

If you want the latest per table1_id , you first need to select the newest record per id, and then query the rest of the record, so something like this: 如果要使用最新的table1_id ,则首先需要选择每个id的最新记录,然后查询其余记录,因此如下所示:

WITH latestprice (
    SELECT table1_id, MAX(price_date) AS price_date
    FROM table2
    GROUP BY table1_id
)
SELECT t2.table2_id, t2.table1_id, t2.price, t2.price_date
FROM latestprice l
INNER JOIN table2 t2
    ON t2.table1_ud = l.table1_id AND t2.price_date = l.price_date

If you also want information from table1 , then you need to add an extra join. 如果您还需要table1信息,则需要添加一个额外的联接。 Note that the above query has one flaw: if there are multiple entries for table1_id with the same price_date it will produce multiple rows and duplicates per table_id . 请注意,上面的查询有一个缺陷:如果table1_id多个条目具有相同的price_date ,它将为table_id产生多个行和重复项。 If you want to enforce that this can't happen, you need to add an unique constraint for table1_id, price_date . 如果要强制这种情况不会发生,则需要为table1_id, price_date添加一个唯一约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM