简体   繁体   English

Oracle PL / SQL-根据列的最大值插入值

[英]Oracle PL/SQL - Inserting values based on max of columns

I am trying to insert data (product, timestamp) into a table xyz from tables A, B & C with a primary key as PRODUCT. 我正在尝试将主键为PRODUCT的数据(产品,时间戳)从表A,B和C插入表xyz。 All the three table have a timestamp column along with other columns. 所有这三个表都有一个timestamp列以及其他列。 I want to insert row with product and max of timestamp of these three tables (A, B & C). 我想插入这三个表(A,B和C)的乘积和时间戳的最大值。

You don't specify what you want to happen if product already exists in table xyz, so on the assumption that it doesn't, you could use a query like this: 如果表xyz中已经存在产品,则无需指定要发生的事情,因此,在不存在该假设的情况下,可以使用如下查询:

Insert into XYZ(Product, Timestamp)
Select Product, max(timestamp)
  from (select product, timestamp from a union all
        select product, timestamp from b union all
        select product, timestamp from c)
 group by product

You might try the following: 您可以尝试以下方法:

INSERT INTO xyz
  ( product, timestamp )
SELECT MAX(product) KEEP ( DENSE_RANK FIRST ORDER BY timestamp DESC ) AS product
     , MAX(timestamp)
  FROM a
 UNION ALL
SELECT MAX(product) KEEP ( DENSE_RANK FIRST ORDER BY timestamp DESC ) AS product
     , MAX(timestamp)
  FROM b
 UNION ALL
SELECT MAX(product) KEEP ( DENSE_RANK FIRST ORDER BY timestamp DESC ) AS product
     , MAX(timestamp)
  FROM c;

Hope this helps. 希望这可以帮助。

UPDATED as per Sentine's comment: 根据Sentine的评论更新

Try this (syntax not verified): 试试这个(语法未验证):

INSERT INTO xyz (product , timestamp) 
 (
    SELECT product , MAX(A.timestamp) 
      FROM A
    UNION
    SELECT product , MAX(B.timestamp) 
      FROM B
    UNION
    SELECT product , MAX(C.timestamp) 
      FROM C
) ;

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

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