对具有多个连接的不同行求和

SUM over distinct rows with multiple joins

我需要创建一个查询,根据资源名称、人名和人的 uf 代码得出 2006 年 1 月 1 日至 2006 年 1 月 31 日之间移动的订单总数,无论人、资源、 uf 字段已填充。

我目前有这个咨询。

Create table Ordered(
    oid int,        
    movement date,     
    pid int,        
    rid int,          
    amount double,     
    unitary double,
    total double, 
    Primary key (OID),
    Constraint fk_PID Foreign key (PID) references People (PID),
    Constraint fk_RID Foreign key (RID) references Resource (RID)
    );

Create table Resource(
    rid int,          
    code Varchar(25),     
    name Varchar(150),        
    Primary key (RID)
    );
    
Create table People(
    pid int,          
    code varchar(25),     
    name varchar(150),        
    FU int,        
    Primary key (PID),
    Constraint fk_FID Foreign key (FID) references FU (FID)
    );
    
Create table FU(
    fid int,          
    code varchar(25),     
    name varchar(150),
    Primary key (Fid)
    );

select r.name,p.name,f.code,sum(o.total) from Ordered o 
    right join resource r on o.rid = r.rid right join 
    People p on o.pid = p.pid 
    right join fu f on p.fid = f.fid where o.movement >= '2006-01-01' and o.movement <= '2006-01-31' group by r.name,p.name,f.code

我的问题是,当资源或人员为空时,查询未列出

使用以下查询 (http://www.sqlfiddle.com/#!9/c0f4fe/4)

我不是 100% 确定你想要什么。但是如果你想列出所有 ,即使是那些没有订单的人,那么从 people 开始并使用 left join:

select r.name, p.name, f.code,sum(o.total)
from People p left join
     Ordered o
     on o.pid = p.pid and
        o.movement >= '2006-01-01' and o.movement <= '2006-01-31' left join
     resource r
     on o.rid = r.rid left join
     fu f
     on p.fid = f.fid 
group by r.name,p.name,f.code