2012-02-23 59 views
3

我有以下表格:SQL:加入3代表与资金,对非聚合列过滤

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子句中使用的:两个日期之间。

任何人都可以帮忙吗?

回答

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 
+0

感谢您的支持,此功能完美无缺。现在我要将空结果返回,我需要能够通过工厂过滤未设置的enddate标志。这个查询可能吗? – user1228983 2012-02-23 21:01:41

+0

@ user1228983'endDate'标志在哪里?这是“植物”表中的另一列吗? – 2012-02-23 21:06:15

+0

是的,对不起。我遗漏了我认为无关紧要的东西,保持帖子整洁! – user1228983 2012-02-23 21:10:09

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 


你让使用ID所有表之间的INNER JOIN。之后,您只需要QuantitiesSUM,PartsRejects。为此,您需要使用GROUP BY

+0

嗨。感谢您的回复,但这不允许我按日期过滤。 – user1228983 2012-02-23 17:50:02

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 

请注意,这不会有任何次品或部分获得的植物。