0

我试图通过将连接更改为 study 和 id 和 date<->date -1 来转换我的查询(在一个表上是正常数据,在另一个表中是 date-1),但我正在做一些错误,这给了我一个错误。

数据库:Oracle 并在 Denodo Server 上运行

外科医生

study id        cal_dtm    total
RSCLS CA10001  2020-08-11    52
RSCLS CA10001  2020-08-10    52
ETDLD CA20302  2020-08-11    99
ERGKG CA34524  2020-08-11    31

询问:

  select
  tt1.study,
  tt1.id,
  tt1.cal_dtm,
  tt1.total,
  tt1.total-coalesce(tt2.total, 0) as delta
  from pedics tt1
  left outer JOIN pedics tt2 on tt1.total = tt2.total
    and extract(month from tt1.cal_dtm)-extract(month from tt2.cal_dtm)=1

使用引发错误的所需条件进行查询:

select
  tt1.study,
  tt1.id,
  tt1.cal_dtm,
  tt1.total,
  (tt1.total-coalesce(tt2.total 0)) as delta
  from pedics tt1
  left outer JOIN pedics tt2 on tt1.study_name = tt2.study_name and tt1.site_id = tt2.site_id
  and extract(month from tt1.cal_dtm)-extract(month from tt2.cal_dtm-1)

错误:连接视图条件错误:函数“-(tt2.cal_dtm, '1')”的参数类型无效

4

1 回答 1

0

如果您正在寻找该行中的一天与前一天之间的增量,则使用 LAG 分析函数效率更高。这样您就可以查看前一行的“总计”并找到当前行总计之间的差异。

设置

我添加了比您提供的更多示例数据以显示更多案例。

CREATE TABLE pedics
(
    study      VARCHAR2 (5),
    id         VARCHAR2 (7),
    cal_dtm    DATE,
    total      NUMBER
);

INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('RSCLS', 'CA10001', DATE '2020-08-11', 52);
INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('RSCLS', 'CA10001', DATE '2020-08-10', 52);
INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('RSCLS', 'CA10001', DATE '2020-08-09', 50);
INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('ETDLD', 'CA20302', DATE '2020-08-11', 99);
INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('ERGKG', 'CA34524', DATE '2020-08-11', 31);
INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('ERGKG', 'CA34524', DATE '2020-08-12', 35);
INSERT INTO pedics (study, id, cal_dtm, total) VALUES ('ERGKG', 'CA34524', DATE '2020-08-13', 26);

询问

  SELECT p.*, total - LAG (total) OVER (PARTITION BY study, id ORDER BY cal_dtm) AS delta
    FROM pedics p
ORDER BY study, id, cal_dtm;

结果

STUDY | ID      | CAL_DTM   | TOTAL | DELTA
--------------------------------------------
ERGKG | CA34524 | 8/11/2020 |    31 | 
ERGKG | CA34524 | 8/12/2020 |    35 | 4
ERGKG | CA34524 | 8/13/2020 |    26 | -9
ETDLD | CA20302 | 8/11/2020 |    99 | 
RSCLS | CA10001 | 8/9/2020  |    50 | 
RSCLS | CA10001 | 8/10/2020 |    52 | 2
RSCLS | CA10001 | 8/11/2020 |    52 | 0
于 2020-09-03T21:17:02.990 回答