簡體   English   中英

尋找兩個數據輸出之間的差距

[英]Finding gap between two data outputs

因此,當我需要找到總員工的兩個平均工資之間的差距時,我遇到了這個問題,這意味着所有員工都在從事一個項目,而所有員工都沒有在一個項目上工作。 (或者如果你願意,屬於一個項目)

這是相關表格:

create table employee (
    eid numeric(5,0),
    ename varchar(30),
    salary integer,
    did numeric(3,0),
    classification integer,
    primary key(eid),
    foreign key(did)references department
);

create table onproject(
    pid numeric(3,0),
    eid numeric(5,0),
    fdate date,
    primary key(pid,eid),
    foreign key (eid) references employee,
    foreign key (pid) references project
);

請記住,我不能改變表格的編寫方式。 我的想法是為那些目前不屬於任何項目的員工創建 AVG,反之亦然,我已經設法做到了:

select count(employee.eid),avg(salary) 
from employee
where employee.eid not in select onproject.eid from onproject

但不幸的是在那之后不多

您可以通過將employee左連接到onproject然后使用條件聚合來完成:

select
  avg(case when t.ison is not null then t.salary end) - 
  avg(case when t.ison is null then t.salary end) gap
from (  
  select e.eid, e.salary, max(o.eid) ison 
  from employee e left join onproject o
  on o.eid = e.eid
  group by e.eid, e.salary
) t  

您可以按照以下步驟進行:

select
    avg(salary) filter(where has_project = 1) avg_salary_on_project
    avg(salary) filter(where has_project = 0) avg_salary_not_on_project
from (
    select 
        eid,
        salary,
        case when exists (select 1 from onproject o where o.eid = e.eid) 
            then 1
            else 0
        end has_project
    from employee e
) t

內部查詢使用內聯子查詢來識別每個員工是否至少屬於一個項目。 這會生成一個名為has_project的布爾列 ( 0/1 )。 外部查詢使用該列進行條件平均。

暫無
暫無

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

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