簡體   English   中英

oracle數據庫如何比較2個表

[英]how to compare 2 tables oracle database

表格1

我們有 ID 作為主鍵和他自己的薪水

ID 姓名 薪水
1 " X " 500
2 " Y " 1000
3 " Z " 1500

表 2

我們有來自支付系統的數據

ID 日期 薪水
1 " 6/22/2020 " 500
2 " 6/25/2020 " 1000
3 " 8/05/2021 " 1500

我想要一個查詢來將表 2 中的項目與表 1 進行比較,我的目標是確保每個員工都能得到表 1 中的確切工資

例子

工資為 500 的員工“1”假設一個月他只收到 300 想要檢索員工

* 首選:計算在他的工作時間中有多少個月他沒有得到確切的薪水,並計算出多少差額 $

* 注意:雇員的薪水可能低於或高於他的薪水

這樣的事情應該這樣做:

select
  t1.salary as t1_salary,
  t2.*
from 
  t1 left outer join t2 on t1.id = t2.id

ID上連接表並將差異放入where子句。

示例數據(您擁有它並且您不必輸入):

SQL> with
  2  table1 (id, name, salary) as
  3    (select 1, 'x',  500 from dual union all
  4     select 2, 'y', 1000 from dual
  5    ),
  6  table2 (id, datum, salary) as
  7    (select 1, date '2022-01-01',  500 from dual union all
  8     select 1, date '2022-02-01',  300 from dual union all
  9     select 1, date '2022-03-01',  500 from dual union all
 10     select 1, date '2022-04-01',  700 from dual union all
 11     select 2, date '2022-01-01', 1000 from dual union all
 12     select 2, date '2022-02-01', 1000 from dual union all
 13     select 2, date '2022-03-01',  900 from dual union all
 14     select 2, date '2022-04-01', 1200 from dual
 15    )

查詢從這里開始:

 16  select a.id,
 17    a.name,
 18    b.datum,
 19    b.salary - a.salary as difference
 20  from table1 a join table2 b on a.id = b.id
 21  where b.salary - a.salary <> 0;

        ID NAME DATUM      DIFFERENCE
---------- ---- ---------- ----------
         1 x    01.02.2022       -200
         1 x    01.04.2022        200
         2 y    01.03.2022       -100
         2 y    01.04.2022        200

SQL>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM