2012-02-23 79 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 

請注意,這不會有任何次品或部分獲得的植物。