0

我想使用 INSERT 语句将数据添加到表 STATISTICS。

当新数据进入时,我还想将新计数移至旧计数并将新日期移至旧日期。

这就是它变得棘手的地方,因为我不知道 Oracle 中是否存在带有 SET 的 INSERT INTO 表之类的东西。

INSERT INTO STATISTICS
SET 
    MODEL = '&MY_MODEL',
    NEW_COUNT = 
    (
        SELECT COUNT(*)
        FROM TABLE CLIENTS
    ),
    NEW_DATE = SYSDATE,
    OLD_COUNT = NEW_COUNT,
    OLD_DATE = NEW_DATE,
    PRNCT_CHANGE =  ((NEW_COUNT) - (OLD_COUNT)) / (NEW_COUNT)*100
);

我如何在 Oracle 中实现这一点?

4

2 回答 2

1

这应该更新统计数据,随时添加新的统计数据。它假定 MODEL 上的唯一键;如果这不是真的,那么您必须按照安吉丽娜的说法进行插入,只获取单个 MODEL 条目的最新行。

MERGE INTO STATISTICS tgt
using (SELECT '&MY_MODEL' AS MODEL,
              (SELECT COUNT(*) FROM CLIENTS) AS NEW_COUNT,
              SYSDATE AS DATE_COUNT,
              NULL AS OLD_COUNT,
              NULL OLD_DATE,
              NULL AS PRCNT_CHANGE
         FROM DUAL) src
   on (TGT.MODEL = SRC.MODEL)
WHEN MATCHED THEN UPDATE 
     SET TGT.NEW_COUNT = SRC.NEW_COUNT,
         TGT.NEW_DATE  = SRC.NEW_DATE,
         TGT.OLD_COUNT = TGT.NEW_COUNT,
         TGT.OLD_DATE  = TGT.NEW_DATE,
         TGT.PRCNT_CHG = 100 * (SRC.NEW_COUNT - TGT.NEW_COUNT) / (SRC.NEW_COUNT)
            -- NEEDS DIV0/NULL CHECKING
WHEN NOT MATCHED THEN INSERT
    (MODEL, NEW_COUNT, NEWDATE, OLD_COUNT, OLD_DATE, PRCNT_CHANGE)
  VALUES
    (src.MODEL, src.NEW_COUNT, src.NEWDATE, src.OLD_COUNT, src.OLD_DATE, src.PRCNT_CHANGE);
于 2013-07-17T03:25:09.327 回答
0
INSERT INTO STATISTICS(MODEL,NEW_COUNT,NEW_DATE,OLD_COUNT,OLD_DATE,PRNCT_CHANGE)
SELECT MODEL, 
       (  SELECT COUNT(*)
          FROM TABLE(USERS)
       ),
       SYSDATE,
       NEW_COUNT,
       NEW_DATE,
       (((NEW_COUNT) - (OLD_COUNT)) / (NEW_COUNT)*100)
FROM SEMANTIC.COUNT_STATISTICS
WHERE MODEL = '&MY_MODEL'
AND trunc(NEW_DATE) = trunc(NEW_DATE -1)
;
于 2013-07-16T20:01:17.743 回答