SQL:使用sum连接3个表,过滤非聚合列

时间:2012-02-23 17:39:33

标签: sql join group-by

我有以下表格:

    Plant:
ID      Name
1       Plant1
2       Plant2
......

   Rejects:
PlantID Quantity  Date
1       20        01/02/2012
1       3         02/02/2012
2       30        03/02/2012
.....

  Parts
PlantID Quantity  Date
1       300       01/02/2012
2       500       01/02/2012
1       600       02/02/2012
.......

我正在尝试加入这三个,这样我就可以在两个日期之间获得每个工厂的一部分和拒绝:

Plant   Parts   Rejects
Plant1       900     23
Plant2       500     30
.....

我尝试过连接,它只是乘以总和,我尝试过的子查询不允许我使用日期过滤器,因为它没有在group by子句中使用。

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

declare @startDate datetime, @endDate datetime
select @startDate = '1/1/2012', @endDate = '2/1/2012'

select
    p.Name as Plant,

    (select sum(Quantity) 
     from Parts 
     where PlantID = p.ID and date between @startDate and @endDate) as Parts,

    (select sum(Quantity) 
     from Rejects 
     where PlantID = p.ID and date between @startDate and @endDate) as Rejects
from
    Plant p
where
    p.endDate is null

答案 1 :(得分:0)

这样可以解决问题:

select p.Name as Plant,
       SUM(t.Quantity) as Parts,
       SUM(r.Quantity) as Rejects
from Plant p
inner join Rejects r on p.ID = r.PlantID
inner join Parts t on p.ID = PlantID
group by p.Name


您使用INNER JOIN在所有表之间建立ID。之后,您只需要SUMQuantitiesParts的{​​{1}}。为此,您需要使用Rejects

答案 2 :(得分:0)

以下应该有效(使用oracle):

SELECT NVL(p.plantid, r.plantid), NVL(parts,0), NVL(rejects,0)
FROM 
    (SELECT plantid, sum(quantity) as parts
    FROM parts
    WHERE date BETWEEN a AND b) p
        FULL JOIN
    (SELECT plantid, sum(quantity) as rejects
    FROM rejects
    WHERE date BETWEEN a and b) r
       ON p.plantid = r.plantid

请注意,这不会让没有废品或零件的工厂。

相关问题